简体   繁体   中英

Thread Communication when Debug mode and Release Mode

Threads does not communicate each other while release mode but they do communicate while debug mode. Also Threads do communicate if i make thread sleep for 0.1 second while release mode. Why it is happening ? There are example for you.

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.
}

}

And There are working example for you

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.
}

}

They gave you the correct answer in the comments.

Using a plain bool to communicate between threads creates a 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.

The fix is to use std::atomic<bool> instead of bool .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM