此示例在 windows7 和 ideone.com 下打印所有 2 条消息,但无法在 windows xp 上打印第二条消息。我做错了什么?如果它是一个错误,我应该在哪里报告它?
使用 visual studio 2017,平台工具集 v141_xp 为 windows xp 编译。
#include <iostream>
#include <future>
#include <thread>
using namespace std;
int main()
{
auto f1 = async(launch::async, []()->int {
cout << "in outer async" << endl;
auto f2 = async(launch::async, []()->int {
cout << "in inner async" << endl;
return 2;
});
f2.get();
return 1;
});
f1.get();
return 0;
}
当内部函数使用 std::thread 而不是 std::async 时更新 - 它在两个系统上都运行良好
auto f2 = thread([]()->int {
cout << "in inner async" << endl;
return 2;
});
f2.join();
UPD2
visual studio 2017 cl.exe 版本 19.14.26428 工具集 v141_xp
命令行:
/permissive- /Yu"stdafx.h" /GS /GL /analyze- /Wall /Gy /Zc:wchar_t /Zi /Gm- /O2 /sdl /Fd"Release\vc141.pdb" /Zc:inline /fp:precise /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_USING_V110_SDK71_" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oy- /Oi /MD /std:c++17 /FC /Fa"Release\" /EHsc /nologo /Fo"Release\" /Fp"Release\testasync.pch" /diagnostics:classic
UPD3 看起来像 launch::async 在 windows xp 上使用时被忽略
vector<future<void>> v;
for( int i = 0; i < 10; i++ )
v.push_back(async(launch::async, []() {cout << "thread" << endl; this_thread::sleep_for(5s); }));
for( auto &f : v )
f.get();
在 windows7 上这需要大约 6 秒才能完成,在 windows xp 上大约需要 50 秒
最佳答案
在 Windows 上 std::async(...)
位于线程池之上。所以可能会出现死锁。在 f1
中,您运行新任务并调用 f2.get()
,它将阻塞直到 f2
完成。但是,如果 auto f2 = async(...)
选择了运行 f1
的同一个线程,那么就会出现死锁,您的程序将无法完成。如果是,则情况并非如此。
更新
请阅读有关 std::async
的 Microsoft 实现 here .
它说:
The C++ standard states that if policy is launch::async, the function creates a new thread. However the Microsoft implementation is currently non-conforming. It obtains its threads from the Windows ThreadPool, which in some cases may provide a recycled thread rather than a new one. This means that the launch::async policy is actually implemented as launch::async|launch::deferred
还有一个answer ,它揭示了 Microsoft 的 std::async
实现的一个特殊特性:
- It limits the total number of background threads it uses, after which a call to std::async will block until a thread becomes free. On my machine, this number is 768.
因此,我假设,如果您在 ThreadPool 中只有一个线程,那么从任务内部调用 std::async
将会死锁。考虑到您的 UPD3,可能是您的情况。
我真的推荐阅读提到的 answer ,因此您可以理解为什么 Microsoft 的 std::async
不同以及如何正确使用它。
关于c++ - std::async 来自 std::async in windows xp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52736076/