为什么在Visual Studio 2013上的std::this_thread::sleep_for上死锁

Why deadlock on std::this_thread::sleep_for on Visual Studio 2013

本文关键字:thread sleep for 死锁 this 为什么 Studio Visual 2013 上的 std      更新时间:2023-10-16

下面的代码永远无法在VS 2013上打印m4(当然也没有t2t3(。它表现得像一个死锁,我不知道原因。我错过了什么吗?

#include <mutex>
#include <thread>
#include <chrono>
#include <stdio.h>
std::mutex m;
void work()
{
printf("t1n");
m.lock();
printf("t2n");
m.unlock();
printf("t3n");
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("m1n");
m.lock();
printf("m2n");
std::thread *th = new std::thread(work);
printf("m3n");
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
printf("m4n");
m.unlock();
printf("m5n");
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。因此,请谨慎使用它。