c++ - 为什么 C++ 异步在没有 future 的情况下按顺序运行?

标签 c++ multithreading c++11 asynchronous

#include <future>
#include <iostream>

void main()
{
    std::async(std::launch::async,[] {std::cout << "async..." << std::endl; while (1);});
    std::cout << "runing main..." << std::endl;
}

在这段代码中,只会输出“async...”,也就是说这段代码是阻塞在async的。但是,如果我添加 future 并让语句变为:

std::future<bool> fut = std::async([] 
{std::cout << "async..." << std::endl; while (1); return false; });

然后一切顺利(不会阻塞)。我不确定为什么会这样。我认为异步应该在单独的线程中运行。

最佳答案

来自 encppreference.com :

If the std::future obtained from std::async is not moved from or bound to a reference, the destructor of the std::future will block at the end of the full expression until the asynchronous operation completes, essentially making code such as the following synchronous:

std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f()
std::async(std::launch::async, []{ g(); }); // does not start until f() completes

如果我没听错,它来自标准 (N4527) 的这些部分:

§30.6.6 [futures.unique_future]:

~future();

Effects:

— releases any shared state (30.6.4);

§30.6.4#5 [futures.state](重点是我的):

When an asynchronous return object or an asynchronous provider is said to release its shared state, it means:

[...].

— these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.

由于您没有存储第一个 std::async 调用的结果,因此调用了 std::future 的析构函数并且满足所有 3 个条件:

  • std::future 是通过 std::async 创建的;
  • 共享状态尚未就绪(由于无限循环);
  • 没有对这个 future 的剩余引用

...然后调用被阻塞。

关于c++ - 为什么 C++ 异步在没有 future 的情况下按顺序运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816928/

相关文章:

c# - 在 C# 中执行并发任务

c++ - 静态库中对 c++11 原子的 undefined reference

c++ - 为什么 C++ 标准的索引有 "undefined behavior"这个条目?

c++ - gcc -l 选项和 .la 库文件

c++ - 链接错误在 32 位 XP 机器上构建 64 位 Qt 应用程序

c++ - 无法编译包含 "if constexpr"的函数模板实例化

java - 关闭 Hook 与终结器方法

c++ - 从文件夹创建 zip 文件 - 在 C++ 中

java - Spring Batch 中的多线程

c++ - C++11 是否支持 C11 的新特性?