multithreading - std::thread C++ 11 无法解释为什么

标签 multithreading c++11

我在 Ubuntu 13.04 桌面上运行这个非常简单的程序,但是如果我注释掉 sleep_for 行,它会在从 main 打印 cout 后挂起。谁能解释为什么?据我了解, main 是一个线程, t 是另一个线程,在这种情况下,互斥锁管理共享 cout 对象的同步。

#include <thread>
#include <iostream>
#include <mutex>

using namespace std;
std::mutex mu;

void show()
{
 std::lock_guard<mutex> locker(mu);
 cout<<"this is from inside the thread"<<endl;
}

int main()
{
 std::thread t(show);
 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
 std::lock_guard<mutex> locker(mu);
 cout<<"This is from inside the main"<<endl;
 t.join();
 return 0;
}

最佳答案

如果你改成如下main函数,代码会按预期工作:

int main()
{
    std::thread t(show);
    {
        std::lock_guard<mutex> locker(mu);
        cout << "This is from inside the main" << endl;
    } // automatically release lock
    t.join();
}

在您的代码中,有一个不幸的竞态条件。如果线程 t 先获得锁,一切正常。但是如果主线程首先获得锁,它会持有锁直到 main 函数结束。这意味着,线程 t 没有机会获得锁,无法完成,主线程将阻塞 t.join()

关于multithreading - std::thread C++ 11 无法解释为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24596061/

相关文章:

c++ - 具有默认类型的可变参数模板

c++ - 如何 std::thread sleep

c++ - 遍历嵌套的 C++11 元组

c# - Mac OS X 上的 Mono - 并行 HTTP 下载限制为 2

c# - 访问 C# 中的处置闭包?

c - 运行程序时出现段错误和变化的输出

c++ - 分配 std::string 时死锁

c# - 等待线程问题

c++ - 随机访问迭代器到 char 数组

c++ - 自定义分配器和内存对齐