C++ 为什么是C++;异步连续运行而不使用未来? #包括 #包括 void main() { std::async(std::launch::async,[]{std::cout
From: 如果从C++ 为什么是C++;异步连续运行而不使用未来? #包括 #包括 void main() { std::async(std::launch::async,[]{std::cout,c++,multithreading,c++11,asynchronous,C++,Multithreading,C++11,Asynchronous,From: 如果从std::async获取的std::future未从引用中移动或绑定到引用,则std::future的析构函数将在完整表达式末尾阻塞,直到异步操作完成,基本上使以下代码同步: std::future<bool> fut = std::async([] {std::cout << "async..." << std::endl; while (1); return false; }); 如果我没有弄错,它来自标准的以下部分(N4527):
std::async
获取的std::future
未从引用中移动或绑定到引用,则std::future
的析构函数将在完整表达式末尾阻塞,直到异步操作完成,基本上使以下代码同步:
std::future<bool> fut = std::async([]
{std::cout << "async..." << std::endl; while (1); return false; });
如果我没有弄错,它来自标准的以下部分(N4527):
§30.6.6[未来.独特的未来]:
~future();
影响:
-释放任何共享状态(30.6.4)
§30.6.4#5[未来州](重点是我的):
当异步返回对象或异步提供程序释放其共享状态时,这意味着:
[……]
-这些操作不会阻止共享状态变为就绪状态,除非它可能会阻止以下所有情况:共享状态是通过调用std::async创建的,共享状态尚未就绪,这是对共享状态的最后一次引用
由于未存储第一次调用的结果,因此调用了std::future
的析构函数,并且满足了所有3个条件:
是通过std::future
创建的std::async
- 共享状态尚未就绪(由于您的无限循环)
- 没有关于这一未来的剩余参考
…然后调用被阻塞。请注意,async不能保证启动新线程。我可以。非常感谢!这正是我要找的。
std::future<bool> fut = std::async([]
{std::cout << "async..." << std::endl; while (1); return false; });
std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f()
std::async(std::launch::async, []{ g(); }); // does not start until f() completes