我的问题是我不知道如何正确使用互斥。我知道理论上它是如何工作的,但我不知道为什么它不能在我的代码中工作,我想如果我在变量上使用互斥,它将被阻塞,直到它被解锁。然而,看起来我仍然有一场数据竞赛。
我尝试在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;
}
}
}
结果应该是我得到了一些输出,所以我现在可以工作了。
发布于 2019-04-16 06:24:32
正如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++;
}
};
https://stackoverflow.com/questions/55697873
复制相似问题