#include <future>
#include <iostream>
void main()
{
std::async(std::launch::async,[] {std::cout << "async..." << std::endl; while (1);});
std::cout << "runing main..." << std::endl;
}
在这段代码中,只会输出“async...”,也就是说这段代码是阻塞在async的。但是,如果我添加 future 并让语句变为:
std::future<bool> fut = std::async([]
{std::cout << "async..." << std::endl; while (1); return false; });
然后一切顺利(不会阻塞)。我不确定为什么会这样。我认为异步应该在单独的线程中运行。
最佳答案
来自 encppreference.com
:
If the
std::future
obtained fromstd::async
is not moved from or bound to a reference, the destructor of thestd::future
will block at the end of the full expression until the asynchronous operation completes, essentially making code such as the following synchronous:std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f() std::async(std::launch::async, []{ g(); }); // does not start until f() completes
如果我没听错,它来自标准 (N4527) 的这些部分:
§30.6.6 [futures.unique_future]:
~future();
Effects:
— releases any shared state (30.6.4);
§30.6.4#5 [futures.state](重点是我的):
When an asynchronous return object or an asynchronous provider is said to release its shared state, it means:
[...].
— these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.
由于您没有存储第一个 std::async
调用的结果,因此调用了 std::future
的析构函数并且满足所有 3 个条件:
std::future
是通过std::async
创建的;- 共享状态尚未就绪(由于无限循环);
- 没有对这个 future 的剩余引用
...然后调用被阻塞。
关于c++ - 为什么 C++ 异步在没有 future 的情况下按顺序运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816928/