c++ - std::async,std::promise 和 std::packaged_task 会阻塞主线程,它们是什么意思?

标签 c++

<分区>

std::async 如下阻塞了我的 UI 线程,这不是我所期望的。 那么,std::async、std::promise 和 std::packaged_task 的含义是什么?

#include <iostream>
#include <thread>
#include <future>
#include "widget.h"
#include "ui_widget.h"

void func_cb()
{
    for ( int i = 0; i < 1000; ++i ) {
        std::cout << "do something..." << std::endl;
        std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) );
    }
}

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    std::async( std::launch::async, func_cb );
}

Widget::~Widget()
{
    delete ui;
}

最佳答案

std::async 返回代码不保存的 std::futurestd::future 的析构函数会阻塞线程,直到值可用。

代码可能需要保存 std::async 的返回值或使用分离的 std::thread 代替。

关于c++ - std::async,std::promise 和 std::packaged_task 会阻塞主线程,它们是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56523435/

相关文章:

c++ - 使用未知指针类型调用函数重载

c++ - 模板 - 传递变量而不是值

c++ - 如何将指针拖到类对象的指针内并递归分配它们然后返回指针? C++

c++ - 尝试编译文件时出现极其奇怪的错误

c++ - 条件模板变量

c++ - 遍历特征矩阵的最有效方法

c++ - C++二进制文件数据解析 : and the right STL for it?

c++ - libpng 错误未被 try/catch block 捕获

c++ - 在模板评估期间允许隐式类型转换

C++11:thread_local 或 OpenCL 1.2 cl_kernel 对象数组?