【发布时间】: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