std::async won#39;t spawn a new thread when return value is not stored(未存储返回值时,std::async 不会产生新线程)
问题描述
考虑我有lamba foo 它只做一些事情并且不需要返回任何东西.当我这样做时:
Consider I have lamba foo which just does some stuff and doesn't need to return anything.
When I do this:
std::future<T> handle = std::async(std::launch::async, foo, arg1, arg2);
一切正常,lamba 将在新线程中生成.但是,当我不存储 std::async 返回的 std::future 时,foo 将在主线程中运行并阻塞它.>
Everything runs fine and the lamba will be spawned in a new thread.
However, when I don't store the std::future which the std::async returns, the foo will be run in the main thread and block it.
std::async(std::launch::async, foo, arg1, arg2);
我在这里遗漏了什么?
推荐答案
来自 just::thread 文档:
如果策略是 std::launch::async 然后在它自己的线程上运行 INVOKE(fff,xyz...).当该线程完成时,返回的 std::future 将准备就绪,并将保存函数调用抛出的返回值或异常.与返回的 std::future 的异步状态相关联的最后一个 future 对象的析构函数应阻塞,直到 future 准备好.
If policy is
std::launch::asyncthen runsINVOKE(fff,xyz...)on its own thread. The returnedstd::futurewill become ready when this thread is complete, and will hold either the return value or exception thrown by the function invocation. The destructor of the last future object associated with the asynchronous state of the returnedstd::futureshall block until the future is ready.
在
std::async(std::launch::async, foo, arg1, arg2);
返回的 future 不会在任何地方赋值,它的析构函数会阻塞直到 foo 完成.
The returned future is not assigned anywhere and its destructor blocks until foo finishes.
这篇关于未存储返回值时,std::async 不会产生新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:未存储返回值时,std::async 不会产生新线程
基础教程推荐
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
