Im using visual studio 2012 and c++11. I dont understand why this does not work:
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 finishes but I explicity set running
to false
. run
and running
have the same location. I tried to set running
as a single global variable but nothing happens. I tried to pass a pointer value too but nothing.
The threads use the same heap. I really don't understand. Can anyone help me?
Your program has Undefined Behavior, because it introduces a data race on the running
variable (one thread writes it, another thread reads it).
You should use a mutex to synchronize access, or make running
an 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With