下面的代码永远不会在VS 2013上打印m4
(当然也不会打印t2
和t3
)。它的行为就像一个死锁,我不知道原因。有什么我想念的吗?
#include <mutex>
#include <thread>
#include <chrono>
#include <stdio.h>
std::mutex m;
void work()
{
printf("t1\n");
m.lock();
printf("t2\n");
m.unlock();
printf("t3\n");
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("m1\n");
m.lock();
printf("m2\n");
std::thread *th = new std::thread(work);
printf("m3\n");
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
printf("m4\n");
m.unlock();
printf("m5\n");
th->join();
return 0;
}
编辑:是的,我看不到死锁。但只要在VS 2013中尝试即可。它会锁定。我想知道原因。这是VS错误还是出了点问题?
程序以以下输出运行:
m1
m2
t1
m3
它阻塞在std::this_thread::sleep_for(std::chrono::milliseconds(1000));
永远,但为什么呢?
我认为这是VS 2013更新5中的错误。在Ubuntu 16.04.5中使用GCC 6.0无法重现此问题。此外,这可能是与std::this_thread::sleep_for
功能相关的错误,导致std::mutex
内部死锁。因此,请谨慎使用。