Multithreading 标准:螺纹C++;11无法解释原因

Multithreading 标准:螺纹C++;11无法解释原因,multithreading,c++11,Multithreading,C++11,我在Ubuntu13.04桌面上运行这个非常简单的程序,但是如果我注释掉sleep_for一行,它会在从main打印cout后挂起。有人能解释为什么吗?据我所知,main是一个线程,t是另一个线程,在本例中,互斥体管理共享cout对象的同步 #include <thread> #include <iostream> #include <mutex> using namespace std; std::mutex mu; void show() { std

我在Ubuntu13.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;
}
#包括
#包括
#包括
使用名称空间std;
std::互斥mu;
无效显示()
{
std::锁柜(mu);

cout如果按如下方式更改为
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();
}
intmain()
{
标准:螺纹t(显示);
{
std::锁柜(mu);

cout这只是一个典型的死锁:主线程获得锁,然后在连接另一个线程时阻塞,但另一个线程只有在成功获得锁的情况下才能连接。

这就是一个常见的代码质量要求的原因,即任何析构函数有副作用的对象都必须在作用域的开头创建,除非这是不这样做的一个很好的理由。