std :: thread c ++。更多线程相同的数据 [英] std::thread c++. More threads same data
问题描述
Im使用visual studio 2012和c ++ 11。我不明白为什么这不工作:
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();
}
在这种情况下,线程的循环 t
从不结束,但我明确设置运行
到 false
。 运行
和运行
具有相同的位置。我试图将运行
设置为单个全局变量,但什么也没有发生。我试图传递一个指针值,但没有什么。
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).
访问或使运行
原子
:
#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";
}
查看工作实例。
这篇关于std :: thread c ++。更多线程相同的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!