我的问题是我不知道如何正确使用互斥体。我理解它在理论上是如何工作的,但我不知道为什么它在我的代码中不起作用。我想如果我在 var 上使用互斥锁,它将被阻止直到它被解锁。尽管如此,我似乎仍然存在数据竞争。
我试图在通过引用传递的 main 中定义一个类互斥锁和一个互斥锁。不知何故,这一切都不起作用。
class test {
public:
void dosmth(std::mutex &a);
int getT(){return t;};
private:
int t = 0;
};
void test::dosmth(std::mutex &a) {
for(;;){
a.lock();
t++;
if(t==1000){
t=0;
}
a.unlock();
}
}
int main() {
test te;
std::mutex help;
std::thread t(&test::dosmth, std::addressof(te), std::ref(help));
for(;;){
for (int i = 0; i <te.getT() ; ++i) {
std::cout<<te.getT()<<std::endl;
}
}
}
结果应该是我得到了一些输出,所以我现在可以让它工作了。
最佳答案
正如 Michael 所提到的,您应该同步读取器和写入器以避免未定义的行为。不是将 mutex
作为参数传递,一种常见的模式是使 mutex
成为对象 (te
) 的成员,锁定和解锁每次(首选 lock_gaurd
而不是手动锁定和解锁)您输入一个成员函数(修改对象的内部状态)。这是一些伪代码:
class Foo{
std::mutex m; // reader and writer are sync'ed on the same mutex
int data_to_sync;
public:
int read(){
lock_gaurd<mutex> lg(m); //RAII lock
return data_to_sync;
//automagically released upon exit
}
void write(){
lock_gaurd<mutex> lg(m);
data_to_sync++;
}
};
关于c++ - 如何正确使用互斥量作为线程中成员函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55697873/