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.

In following code, main thread waits for the completion of foo() on the thread created by async call.

#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

The destructor of the last future object associated with the asynchronous state of the returned std::future shall block until the future is ready.

My question is:

  • Q1. Does this behavior conform to the current C++ standard?
  • Q2. If Q1's answer is yes, which statements say that?

  • Yes, this is required by the C++ Standard. 30.6.8 [futures.async] paragraph 5, final bullet:

    — 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.

    The destructor of the one and only std:future satisfies that condition, and so has to wait for the completion of the thread.

    链接地址: http://www.djcxy.com/p/5200.html

    上一篇: 用自己的版本替换std :: async,但std :: promise应该在哪里?

    下一篇: std :: launch :: async策略的std :: async的行为