std :: list <std :: future>析构函数不会阻止

昂吉

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

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

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

我的印象是,让列表超出范围应该阻塞,直到所有线程返回其主函数为止,因为列表的析构函数将破坏所有std :: future元素,而那些析构函数将等待线程完成。

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

当我尝试此操作时,它没有阻止,我不得不添加

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

到函数末尾,以正确阻止。

我是否有误解,还是必须以其他方式创建线程来执行我在这里想要做的事情?

TC

这是MSVC的bug已被修正,但直到MS发布了Visual C ++的新版本,在2015年可能有一段时间的修复将无法提供(这也是在CTP新版本,但它是一个相当将其用于任何生产代码的好主意...)

正如Scott Meyers在其博客文章中所解释的那样,要求阻塞使用该策略std::futurestd::async调用返回的析构函数,launch::async直到生成的线程完成执行为止(第30.6.8节[futures.async] / p5):

如果实施选择launch::async政策,

  • [...]
  • 相关联的线程完成(1.10)成功检测共享状态的就绪状态的第一个函数的返回值或释放共享状态的最后一个函数的返回值同步(以先发生者为准)。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Visual Studio中,当与std :: async一起使用时,不会调用“ thread_local”变量析构函数,这是一个错误吗?

std :: async(std :: launch :: deferred)+ std :: future :: then的行为

C ++中的std :: promise和std :: future

std :: future作为函数C ++的参数

std :: move意外调用析构函数

std :: list的擦除成员函数是否为所有存储的元素调用析构函数?

了解std :: future :: then的延续

std :: remove_if是否调用析构函数?

std :: future是否等待销毁

std :: future是否会等待?

使用std :: initializer_list构造函数而不会产生歧义?

std :: future with std :: promise

std :: unique_ptr析构函数构造函数顺序

无法手动调用std :: string的析构函数

什么时候调用std :: thread析构函数?

std :: future.wait_for永远阻止

std :: future :: get()或std :: future :: wait()替代std :: thread :: join()吗?

无法调用返回结果的函数:发现不透明类型impl std :: future :: Future

std :: vector析构函数中的分段错误

为什么std :: vector的构造函数调用自定义类的析构函数?

如何终止std :: future?

'future'不是'std'的成员

为什么从`std :: async`阻塞返回的是将来的析构函数?

std :: swap在构造函数,赋值运算符和析构函数方面如何工作?

可连接std :: thread的析构函数

反复调用std :: future :::

std :: map <struct,int>我需要析构函数吗?

如何显式调用 std 迭代器的析构函数?

std::map 对象析构函数被调用?