I'm trying to create a wrapper class W
in C++, which is constructed with a pointer to a generic object OBJ
.
When you call one of OBJ
methods through W
, W
(containing a condition variable cv
) issues a cv.wait()
before calling OBJ
method and a cv.notify()
when OBJ
method has finished.
I've been able to do it with inheritance for a specific class, but would like a generic approach like the one described above.
This is the inheritance approach:
struct A
{
virtual void foo(int i) { bar = i; };
int bar;
};
struct B : public A
{
void foo2(int i)
{
cv.wait(lck);
this->foo(i);
cv.notify_one();
}
std::condition_variable cv;
std::unique_lock<std::mutex> lck;
};
I would like something in like:
template<class T>
struct C
{
C(T *t) : t(t) {}
T *operator->()
{
cv.wait(lck);
return t;
// notify_one when function has completed
}
T *t;
std::condition_variable cv;
std::unique_lock<std::mutex> lck;
};
I found an answer using only locks (but that is not really a monitor): https://stackoverflow.com/a/48408987