Std :: thread C ++. More topics the same data

Im using visual studio 2012 and C ++ 11. I don't understand why this is not working:

void client_loop(bool &run) { while ( run ); } int main() { bool running = true; std::thread t(&client_loop,std::ref(running)); running = false ; t.join(); } 

In this case, the loop of thread t never ends, but I explicability is set to running false . run and running have the same location. I tried setting running as one global variable, but nothing happens. I also tried to pass the value of the pointer, but nothing.

Threads use the same heap. I really do not understand. Can anybody help me?

+6
source share
2 answers

Your program has Undefined Behavior , because it enters the data race in the running variable (one thread writes it, another thread reads it).

You must use the mutex to synchronize access or make running a atomic<bool> :

 #include <iostream> #include <thread> #include <atomic> void client_loop(std::atomic<bool> const& run) { while (run.load()); } int main() { std::atomic<bool> running(true); std::thread t(&client_loop,std::ref(running)); running = false ; t.join(); std::cout << "Arrived"; } 

See a working live example .

+11
source

const probably doesn’t affect the way the compiler compiles. In a single-threaded application, the value will not change (and this particular program does not make sense). In a multi-threaded application, since it is an atomic type, the compiler cannot optimize loading, so there is actually no real problem here. It really is a matter of style; since main changes the value, and client_loop looking for this modification, it doesn't seem right for me to say that the value is const .

0
source

All Articles