我在 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/