Debug模式和Release模式下的线程通信

Thread Communication when Debug mode and Release Mode

线程在发布模式下不相互通信,但在调试模式下它们会通信。如果我在释放模式下让线程休眠 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.
}

}

他们在评论中给了你正确答案。

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

When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race unless

  • both evaluations execute on the same thread or in the same signal handler, or
  • both conflicting evaluations are atomic operations (see std::atomic), or
  • one of the conflicting evaluations happens-before another (see std::memory_order)

If a data race occurs, the behavior of the program is undefined.

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