为什么std::async即使指定了std::launch::async标志,也要同步调用函数?
Why does std::async call the function synchronously even with the specified std::launch::async flag
我传递给std::async的函数打印当前线程id。尽管使用std::launch::async标志调用,它打印相同的头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();
}
}
输出如下:2093620936209362093620936
环境: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();
}
}
你的future生命周期结束于函数每次迭代的作用域。与它关联的线程也会死亡。实现以后可以自由地重用它,即在循环的下一次迭代中。
如果您修改示例代码以打印当前线程id,您将看到当前线程是不同的:
for (int i = 0; i < 5; ++i)
{
PrintThreadId();
auto f = std::async(std::launch::async, PrintThreadId);
f.wait();
}
现场演示
您还应该考虑返回async
的期货是特殊的-在析构函数中它们会阻塞直到任务未完成。更多关于Scott Meyers博客的信息,在相反的标题下: std::futures
来自std::async
并不特殊
相关文章:
- 为什么std::async使用同一个线程运行函数
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 使用 std::async 时死锁,将来作为成员
- 为什么我不能将引用作为 std::async 的函数参数传递
- std::async from std::async in windows xp
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- std::async 不会立即调用
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 可能的 std::async 实现错误 Windows
- C++从 std::async 函数读取命名空间中的全局变量标志
- std::async 究竟是如何执行的?
- 使用 g++8 和 c++20 的 std::async 编译问题
- 如何有效地使用 std::async 对指针数组执行操作
- 如何从 std::async 任务返回 std::tuple
- 使用 std::bind 将 QTimer::singleShot 传递给 std::async
- 如何将函数及其参数传递给成员函数内的 std::async
- 从 VS2013 到 VS2017 std::async 不会启动新线程
- 使用 std::async 调用模板函数的正确方法是什么?
- C++ - 使用 std::async 时显示进度条
- Clang 崩溃,在 std::async 中出现字符 * 异常