【问题标题】:Why deadlock on std::this_thread::sleep_for on Visual Studio 2013为什么在 Visual Studio 2013 上的 std::this_thread::sleep_for 死锁
【发布时间】:2020-09-18 13:27:08
【问题描述】:

下面的代码永远无法在 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)); 永远阻塞,但为什么呢?

【问题讨论】:

  • @asmmo 这是一个VS生成的main函数。 _t 用于 TCHAR 版本 main 函数。它应该像正常的 main 函数一样工作。
  • 不相关:考虑joining th,而不是while(true)
  • 考虑将关键部分放在自己的代码块中并使用std::scoped_lockstd::lock_guard,具体取决于您可以使用的内容。
  • 请注意while (true); 具有未定义的行为
  • 同样。奇怪的。这是否以更少的元素重现(是否需要线程)?睡眠时间短怎么办?这看起来确实像一个运行时错误。也许相关:stackoverflow.com/questions/54493041/…

标签: c++ multithreading visual-studio c++11 deadlock


【解决方案1】:

我认为这是 VS 2013 更新 5 中的一个错误。在 Ubuntu 16.04.5 中使用 GCC 6.0 无法重现此问题。此外,它可能是与std::this_thread::sleep_for 函数相关的错误,导致std::mutex 的内部死锁。所以,请谨慎使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2020-10-19
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多