我正在对监视器进行编码,以便相互排除对std::list
方法的访问权限
我现在拥有的基本上是这样的:
list<int> l;
class monitor{
public:
void m_add(int x){
//lock use of m_remove
//lock use of m_add
l.push_back(x);
//unlock use of m_add
//unlock use of m_remove
}
void m_remove(int x){
//lock use of m_remove
//lock use of m_contains
//lock use of m_add
l.remove(x);
//unlock use of m_add
//unlock use of m_contains
//unlock use of m_remove
}
bool m_contains(int x){
//lock use of m_remove
bool found = find(l.begin(), l.end(), x) != l.end();
//unlock use of m_remove
return found;
}
private:
mutex mtx_remove;
mutex mtx_add;
mutex mtx_contains;
};
list<int> l;
class monitor{
public:
void m_add(int x){
//lock use of m_remove
//lock use of m_add
l.push_back(x);
//unlock use of m_add
//unlock use of m_remove
}
void m_remove(int x){
//lock use of m_remove
//lock use of m_contains
//lock use of m_add
l.remove(x);
//unlock use of m_add
//unlock use of m_contains
//unlock use of m_remove
}
bool m_contains(int x){
//lock use of m_remove
bool found = find(l.begin(), l.end(), x) != l.end();
//unlock use of m_remove
return found;
}
private:
mutex mtx_remove;
mutex mtx_add;
mutex mtx_contains;
};
在main函数内部,我创建了一个运行add函数的线程,例如我收到了错误
thread t(m.m_add, 1);
我理解(通过查看此处的其他答案)我应该在error: invalid use of non-static member function
中运行线程并将所有方法声明为静态,但我需要按顺序实例化thread t(&monitor::m_add, 1);
的对象创建互斥锁(或锁,或其他)并在main的范围内将它们设为私有。
此案例最合适的解决方案是什么?如果只能在监视器类的范围内访问锁定会很有趣(顺便说一句,我还打算将monitor
放在监视器类中。)
答案 0 :(得分:-1)
您的线程功能必须是静态的。要从线程访问成员函数,请在创建时将指向对象的指针传递给线程函数。