【问题标题】:Thread Communication when Debug mode and Release ModeDebug模式和Release模式下的线程通信
【发布时间】:2020-02-13 12:11:17
【问题描述】:

线程在发布模式下不会相互通信,但在调试模式下它们会进行通信。如果我在释放模式下让线程休眠 0.1 秒,线程也会进行通信。为什么会这样?有例子给你。

main.cpp

int main(){
bool foo=false;


thread tk(control,ref(foo));
tk.detach();
this_thread::sleep_for(1s);
foo=true;
while(true){
//it is for program is not finished

}
}

foo.cpp

void control(bool &x){
while(x==false){
   //When release mode, program cannot go out from this.
}

}

还有适合你的工作示例

main.cpp

int main(){
bool foo=false;


thread tk(control,ref(foo));
tk.detach();
this_thread::sleep_for(1s);
foo=true;
while(true){
//it is for program is not finished

}
}

foo.cpp

void control(bool &x){
while(x==false){
  this_thread::sleep_for(1s);
//it can go out.
}

}

【问题讨论】:

  • 您的代码中有一个数据竞争。将foo 设为std::atomic<bool> 类型的变量。此外,control 需要按引用而不是按值传递其参数。
  • 它解决了我的问题@DanielLangr

标签: c++ multithreading debugging release


【解决方案1】:

他们在 cmets 中给了你正确的答案。

使用普通的bool 在线程之间进行通信会创建一个data race

当一个表达式的计算写入一个内存位置而另一个计算读取或修改相同的内存位置时,表达式被称为冲突。具有两个冲突评估的程序存在数据竞争,除非

  • 两个评估都在同一线程或同一信号处理程序中执行,或者
  • 两个冲突的评估都是原子操作(参见std::atomic),或者
  • 其中一个冲突的评估发生在另一个之前(请参阅std::memory_order

如果发生数据竞争,程序的行为是不确定的。

解决方法是使用std::atomic<bool> 而不是bool

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-20
    • 2011-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多