c++ - std::launch::async 像同步进程一样阻塞

标签 c++ multithreading c++11 asynchronous

我正在运行 Visual Studio 2012 并尝试了解 std::async 的工作原理。我创建了一个非常简单的 C++ 控制台应用程序:

#include "stdafx.h"
#include <future>
#include <iostream>

void foo() {
    std::cout << "foo() thread sleep" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(5));
    std::cout << "foo() thread awake" << std::endl;
}

int main()
{
    std::future<void> res = std::async(std::launch::async, foo);
    res.get();
    std::cout << "MAIN THREAD" << std::endl;

    system("pause");

    return 0;
}

我最初的期望是看到“MAIN THREAD”打印输出出现在之前“foo() thread awake”,因为这两个线程异步运行,而 foo() 由于其休眠行为而落后.然而,实际情况并非如此。对 res.get() 的调用会阻塞,直到 foo() 唤醒,然后它才会到达“MAIN THREAD”打印输出。这表示同步行为,所以我想知道我是否遗漏了什么,或者没有完全掌握实现。我浏览了很多关于这个问题的帖子,但仍然没有任何意义。任何帮助将不胜感激!

最佳答案

 res.get();

阻塞直到异步完成。

http://en.cppreference.com/w/cpp/thread/future/get

无论您如何告诉它运行,get 在完成之前都无法为您提供结果。

关于c++ - std::launch::async 像同步进程一样阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37235155/

相关文章:

C++AMP 在 16 位图像上使用纹理计算梯度

编程到接口(interface)的Java单例枚举?

c++ - 在 std::set 或 std::map 的键中使用 weak_ptr 是否安全

c++ - 使用抽象类的容器来容纳子类

c++ - 如何处理 C++ 异常 3765269347

c++ - 如何在数据库更改时更新 QTableView

c++ - 使用 C++11 随机库生成随机数

java - 如何在自己的类中模拟 ConcurrentModificationException?

c# - ThreadWaitReason - 线程正在等待虚拟内存页到达内存

c++ - 未知容器大小