为什么C ++异步顺序运行而没有未来? [英] Why C++ async run sequentially without future?
问题描述
#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 ...",这意味着该代码在异步时被阻止.但是,如果我添加future并让该语句变为:
In this code, only "async..." will be outputted, which means the code is blocked at async. However, if I add future and let the statement become:
std::future<bool> fut = std::async([]
{std::cout << "async..." << std::endl; while (1); return false; });
然后一切运行顺利(不会被阻止).我不确定为什么会这样发生.我认为异步应该在单独的线程中运行.
Then everything runs smoothly (it will not be blocked). I am not sure why it happen in this way. I think async is supposed to run in a separate thread.
推荐答案
来自 encppreference.com
:
如果从
std::async
获得的std::future
没有从引用中移出或未绑定到引用,则std::future
的析构函数将在完整表达式的末尾阻塞,直到异步操作完成为止,从而使诸如以下同步:
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)的以下部分:
If I did get that right, it comes from these parts of the standard (N4527):
§30.6.6[futures.unique_future]:
~future();
效果:
-释放任何共享状态(30.6.4);
— 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:
[...].
-这些操作不会阻止共享状态准备就绪,除外,如果以下所有条件都为真,则可能会阻止:共享状态是通过调用std :: async创建的,共享状态尚未准备就绪,这是对共享状态的最后引用.
— 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个条件:
Since you did not store the result of your first std::async
call, the destructor of std::future
is called and since all 3 conditions are met:
-
std::future
是通过std::async
创建的; - 共享状态尚未就绪(由于无限循环);
- 没有其他关于这个未来的参考书
- the
std::future
was created viastd::async
; - the shared state is not yet ready (due to your infinite loop);
- there is no remaining reference to this future
...然后通话被阻止.
...then the call is blocking.
这篇关于为什么C ++异步顺序运行而没有未来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!