问题
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?
回答1:
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.
回答2:
The const
probably doesn't affect the compiler's view of the code. In a single-threaded application, the value won't change (and this particular program is meaningless). In a multi-threaded application, since it's an atomic type, the compiler can't optimize out the load, so in fact there's no real issue here. It's really more a matter of style; since main
modifies the value, and client_loop
looks for that modification, it doesn't seem right to me to say that the value is const
.
来源:https://stackoverflow.com/questions/15329234/stdthread-c-more-threads-same-data