微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – std :: list析构函数不会阻塞

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

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

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

我的印象是,让列表超出范围,应该阻止,直到所有线程返回其主要功能,因为列表析构函数将破坏所有std ::未来的元素,而the destructor of those将等待线程完成.

编辑:由于它是相关的,我会在这里添加
这是在Win7与Visual Studio 2013专业版的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在07年2月解释的那样,使用launch :: async策略由std :: async调用返回的std ::未来的析构函数需要阻止,直到产生的线程完成执行(§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.

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

原文地址:https://www.jb51.cc/c/111644.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐