[英]the behavior of std::async with std::launch::async policy
I have some question about behavior of std::async
function with std::launch::async
policy & std::future
object returned from async. 我对std::async
函数的行为有一些疑问, std::launch::async
policy& std::future
object from async。
In following code, main thread waits for the completion of foo()
on the thread created by async
call. 在下面的代码中,主线程等待async
调用创建的线程上的foo()
完成。
#include <thread>
#include <future>
#include <iostream>
void foo()
{
std::cout << "foo:begin" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "foo:done" << std::endl;
}
int main()
{
std::cout << "main:begin" << std::endl;
{
auto f = std::async(std::launch::async, foo);
// dtor f::~f blocks until completion of foo()... why??
}
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "main:done" << std::endl;
}
And I know http://www.stdthread.co.uk/doc/headers/future/async.html says 我知道http://www.stdthread.co.uk/doc/headers/future/async.html说
The destructor of the last future object associated with the asynchronous state of the returned std::future shall block until the future is ready. 与返回的std :: future的异步状态关联的最后一个对象的析构函数将阻塞,直到将来准备就绪。
My question is: 我的问题是:
Yes, this is required by the C++ Standard. 是的,这是C ++标准所要求的。 30.6.8 [futures.async] paragraph 5, final bullet: 30.6.8 [futures.async]第5段,最后一颗子弹:
— the associated thread completion synchronizes with (1.10) the return from the first function that successfully detects the ready status of the shared state or with the return from the last function that releases the shared state, whichever happens first. - 关联的线程完成与(1.10)从成功检测到共享状态的就绪状态的第一个函数的返回或与释放共享状态的最后一个函数的返回同步(以先发生者为准)。
The destructor of the one and only std:future
satisfies that condition, and so has to wait for the completion of the thread. 唯一的std:future
的析构函数满足该条件,因此必须等待线程的完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.