我正在尝试用 C++ 创建一个包装类 W
,它是用指向通用对象 OBJ
的指针构造的。
当您通过 W
调用 OBJ
方法之一时,W
(包含条件变量 cv
)会出现问题调用 OBJ
方法之前的 cv.wait()
以及调用 OBJ
方法完成时的 cv.notify()
.
我已经能够通过特定类的继承来做到这一点,但想要一种像上面描述的那样的通用方法。
这是继承方法:
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;
};
我想要类似的东西:
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;
};
我找到了仅使用锁的答案(但这并不是真正的监视器):https://stackoverflow.com/a/48408987
最佳答案
这是一个工作示例:
#include <iostream>
#include <mutex>
template<class T>
class Wrapper {
std::mutex m;
T* p;
public:
Wrapper(T& t) : p(&t) {}
class Proxy {
std::unique_lock<std::mutex> lock;
T* p;
public:
Proxy(std::mutex& m, T* p)
: lock(m)
, p(p)
{
// Locked the mutex.
std::cout << __PRETTY_FUNCTION__ << '\n';
}
Proxy(Proxy&& b) = default;
~Proxy() {
std::cout << __PRETTY_FUNCTION__ << '\n';
// Unlocked the mutex.
}
T* operator->() const { return p; }
};
Proxy operator->() { return Proxy(m, p); }
};
struct A {
void f() { std::cout << __PRETTY_FUNCTION__ << '\n'; }
};
int main() {
A a;
Wrapper<A> w(a);
w->f();
}
输出:
Wrapper<T>::Proxy::Proxy(std::mutex&, T*) [with T = A]
void A::f()
Wrapper<T>::Proxy::~Proxy() [with T = A]
参见Wrapping C++ Member Function Calls by Bjarne Stroustrup了解完整详细信息。
关于使用条件变量的 C++ 监视器类/包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57857403/