std :: async与std :: launch :: async策略的行为 [英] the behavior of std::async with std::launch::async policy

查看:1420
本文介绍了std :: async与std :: launch :: async策略的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 std :: async 函数的行为有一些问题,其中 std :: launch :: async & std :: future 从异步返回的对象。

I have some question about behavior of std::async function with std::launch::async policy & std::future object returned from async.

在以下代码中,主线程等待完成 foo() 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;
}

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


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

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

我的问题是:


  • Q1。此行为是否符合当前的C ++标准?

  • Q2。如果Q1的回答是yes,哪些语句说?

推荐答案

C ++标准。 30.6.8 [futures.async]第5段,最后一个项目符号:

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


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

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

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

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

这篇关于std :: async与std :: launch :: async策略的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆