std :: thread c ++.更多线程相同的数据

Mat*_*tti 6 c++ heap multithreading std c++11

我使用visual studio 2012和c ++ 11.我不明白为什么这不起作用:

void client_loop(bool &run)
{
    while ( run );
}

int main()
{
    bool running = true;
    std::thread t(&client_loop,std::ref(running));

    running = false ;
    t.join();
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,线程循环t永远不会完成,但我明确地设置runningfalse.runrunning拥有相同的位置.我试图将其设置running为单个全局变量,但没有任何反应.我试图传递一个指针值,但没有.

线程使用相同的堆.我真的不明白.谁能帮我?

And*_*owl 11

您的程序具有未定义的行为,因为它在running变量上引入了数据争用(一个线程写入它,另一个线程读取它).

您应该使用互斥锁来同步访问权限,或者创建running一个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";
}
Run Code Online (Sandbox Code Playgroud)

查看一个有效的实例.