我有一个多线程应用程序,循环等待用户输入为主线程.
在正确的输入上,应该停止循环并等待所有其他线程,以完全结束.
在正确的输入上,应该停止循环并等待所有其他线程,以完全结束.
为此,我创建了一个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
@H_403_42@
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.