Created
October 30, 2013 15:36
-
-
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))
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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