简体   繁体   English

std :: async与std :: launch :: async策略的行为

[英]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: 我的问题是:

  • Q1. Q1。 Does this behavior conform to the current C++ standard? 这种行为是否符合当前的C ++标准?
  • Q2. Q2。 If Q1's answer is yes, which statements say that? 如果Q1的答案是肯定的,哪些陈述说明了?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM