gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:15:32 27 4
gpt4 key购买 nike

下面的代码永远不会在VS 2013上打印m4(当然也没有t2t3)。它的行为就像一个死锁,我不知道原因。我有什么想念的吗?

#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内部死锁。因此,请谨慎使用。

关于c++ - 为什么在Visual Studio 2013的std::this_thread::sleep_for上死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62112004/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com