gpt4 book ai didi

c++ - std::async 与 std::launch::async 策略的行为

转载 作者:IT老高 更新时间:2023-10-28 22:14:07 29 4
gpt4 key购买 nike

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

在以下代码中,主线程在 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;
}

我知道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.

我的问题是:

  • 第一季度。这种行为是否符合当前的 C++ 标准?
  • 第二季度。如果 Q1 的回答是肯定的,哪些陈述是这样说的?

最佳答案

是的,这是 C++ 标准所要求的。 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.

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

关于c++ - std::async 与 std::launch::async 策略的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9733432/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com