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

yoh*_*hjp 17 c++ multithreading c++11

我对从async返回的策略和对象的std::async函数行为有一些疑问.std::launch::asyncstd::future

在下面的代码中,主线程等待foo()通过async调用创建的线程完成.

#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;
}
Run Code Online (Sandbox Code Playgroud)

我知道http://www.stdthread.co.uk/doc/headers/future/async.html

与返回的std :: future的异步状态关联的最后一个对象的析构函数将阻塞,直到将来准备就绪.

我的问题是:

  • Q1.这种行为是否符合当前的C++标准?
  • Q2.如果Q1的答案是肯定的,哪些陈述说明了?

Ant*_*ams 16

是的,这是C++标准所要求的.30.6.8 [futures.async]第5段,最后一颗子弹:

- 关联的线程完成与(1.10)从成功检测到共享状态的就绪状态的第一个函数的返回或与释放共享状态的最后一个函数的返回同步(以先发生者为准).

一个的析构函数只std:future满足该条件,因此必须等待线程的完成.

  • 在本周的C++标准委员会会议上,我们正在积极讨论改变标准的提案.上面的代码仍然可以工作(因为它使用`auto`),但是`std :: async`将不再返回`std :: future` ---它将返回一个`std :: waiting_future`.Herb表示,微软将把他们的代码更改为本周决定的代码(即使这是现状). (2认同)