Skip to content

Instantly share code, notes, and snippets.

@krdln
Created October 30, 2013 15:36
Show Gist options
  • Save krdln/7234713 to your computer and use it in GitHub Desktop.
Save krdln/7234713 to your computer and use it in GitHub Desktop.
Wrapping objects behind mutex. (monitor to zła nazwa (haha, mieszamy języki))
#include <cstdio>
#include <thread>
#include <future>
#include <mutex>
using namespace std;
struct Obiekt {
int x;
void f() { printf("Hej %d!\n", x); }
};
template<class T>
struct Monitor {
T obiekt;
mutex m;
struct Sesja {
T * ptr;
unique_lock<mutex> l;
Sesja(T * ptr, mutex & m) : ptr{ptr}, l{m} { printf("In\n"); }
T * operator -> () { return ptr; }
~Sesja() { printf("Out\n"); }
};
template<class... A> Monitor(A... a) : obiekt{a...} {}
Sesja operator -> () { return { &obiekt, m }; }
};
int main() {
Monitor<Obiekt> mo{42};
auto call_f = [&mo](){ mo->f(); };
auto a1 = async(launch::async, call_f);
auto a2 = async(launch::async, call_f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment