我传递给 std::async 的函数打印当前线程 ID。尽管使用 std::launch::async 标志调用,它仍打印相同的 thead id。这意味着它同步调用该函数。为什么?
void PrintThreadId()
{
std::cout << std::this_thread::get_id() << std::endl;
}
int main()
{
for (int i = 0; i < 5; ++i)
{
auto f = std::async(std::launch::async, PrintThreadId);
f.wait();
}
}
输出是: 20936 20936 20936 20936 20936
环境:VS 2015,W7。
提前致谢!
最佳答案
您实际上通过等待每个调用来序列化调用,因此可以重复使用同一个线程而不会破坏 std::future
由不同于调用者线程
当以下代码显示与其他代码相同的 Caller ThreadId
时,请唤醒我们:
void PrintThreadId()
{
std::cout << std::this_thread::get_id() << std::endl;
}
int main()
{
std::cout << "Caller threadId (to be different from any id of the future exec thread): ";
PrintThreadId();
for (int i = 0; i < 5; ++i)
{
auto f = std::async(std::launch::async, PrintThreadId);
f.wait();
}
}
关于c++ - 为什么即使使用指定的 std::launch::async 标志,std::async 也会同步调用该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200604/