gpt4 book ai didi

c++ - std::list 析构函数不阻塞

转载 作者:可可西里 更新时间:2023-11-01 15:10:24 28 4
gpt4 key购买 nike

我有一个多线程应用程序,有一个循环等待用户输入作为主线程。在正确的输入上,它应该停止循环并等待所有其他线程正确结束。

为此,我创建了一个 std::list,其中放置了为创建线程而创建的 std::future 对象

std::list<std::future<int>> threads;
threads.emplace_front(std::async(std::launch::async, ...));

我的印象是,让 list 超出范围应该阻塞,直到所有线程返回它们的 main 函数,因为 list 的析构函数将 destrurct所有 std::future 元素和 the destructor of those将等待线程完成。

编辑:因为它是相关的,所以我将在此处添加它:这是在 Win7 上使用 Visual Studio 2013 Professional 中的 MSVC 版本/编辑

当我尝试这个时,它没有阻塞,我不得不添加

for (auto it = threads.begin(); it != threads.end(); ++it) {
it->get();
}

到函数末尾,才能正确阻塞。

我是否误解了什么,或者我是否必须以不同的方式创建线程才能在此处执行我想执行的操作?

最佳答案

这是一个 MSVC bug that has been fixed , 但在 MS 发布新版本的 Visual C++ 之前,修复程序将不可用,可能是在 2015 年的某个时间。(它也是 available in the CTP for the new version ,但将它用于任何生产代码是一个非常糟糕的主意......)

正如 Scott Meyers 在 his blog post 中解释的那样,由使用 launch::async 策略的 std::async 调用返回的 std::future 的析构函数需要阻塞直到生成的线程完成执行(§30.6.8 [futures.async]/p5):

If the implementation chooses the launch::async policy,

  • [...]
  • the associated thread completion synchronizes with (1.10) the return from the first function that successfully detects the ready status of the shared state or with the return from the last function that releases the shared state, whichever happens first.

在这种情况下,future 的析构函数是“释放共享状态的最后一个函数”,因此线程完成必须同步(即发生在) 该函数的返回值。

关于c++ - std::list<std::future> 析构函数不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698634/

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