如何从线程返回结果?

std::async ------ 函数模板,启动一个异步任务,返回一个std::future对象

std::future ------ 类模板(#include<future>)

cpp 复制代码
#include <iostream>
#include <thread>
#include <future>
using namespace std;

int mythread() {
    std::chrono::milliseconds dura(2000); // 1000ms = 1s, 2s
    std::this_thread::sleep_for(dura);
    cout << std::this_thread::get_id() << endl;
    return 5;
}

int main() {
    std::future<int> res = std::async(mythread);
    cout << res.get() << endl;
    return 0;
}

通过async创建并运行线程,如果需要传参跟thread方式一样(第二个参数位置。如果是对象的函数,则第二个参数是对象地址,第三个才是参数)

线程会卡在res.get()处,等待线程执行完成(相当于一个while死等,直到拿到结果)。只能get一次。

future<int> res定义res时,已经能够指出返回的类型

如果不需要拿到返回值。直接用res.wait(); 代码卡在这里等待线程返回,但本身不返回结果


可以看出,std::async与std::thread的主要区别在于:当系统资源紧张时,调用std::thread有可能导致线程创建失败,程序崩溃。

且std::thread并不会返回值给主线程

cpp 复制代码
#include <iostream>
#include <thread>
#include <future>
using namespace std;
class A {
public:
    int mythread(int x, int y) {
        std::chrono::milliseconds dura(2000); // 1000ms = 1s, 2s
        std::this_thread::sleep_for(dura);
        cout << std::this_thread::get_id() << endl;
        return x + y;
    }
};

int main() {
    A a;
    int x = 7;
    int y = 8;

    // 常用方式
    std::future<int> res = std::async(&A::mythread, &a, x, y);

    // 此处不会创建新的线程,而是直接在主线程中调用了函数------ 那有什么用呢?
    std::future<int> res1 = std::async(std::launch::deferred,&A::mythread, &a, x, y);
    
    /* 如果希望创建新的线程来执行函数。如果async不带第一个参数创建线程
     * 如果不调用res.get()函数,线程不会异步执行。所以如果明确要使用异步执行,
     * 最好是带着std::launch::async ------ 书友"松鼠."
     *  */
    auto res2 = std::async(std::launch::async, &A::mythread, &a, x, y);
    
    /* (根据系统硬件资源是否即将枯竭)有可能创建新线程。任务可能同步执行,也可能异步执行(创建线程)
     * 如果不带第一个参数,也会默认是该配置。
     *  */
    auto res3 = std::async(std::launch::async | std::launch::deferred, &A::mythread, &a, x, y);
    cout << res.get() << endl;
    return 0;
}

std::async具有不确定性。系统如果决定延迟运行(std::launch::deferred),则std::async创建的任务不会立即执行。(或不调用future的wait()/get(),任务入口函数不会执行)


std::packaged_task类模板,把各种可调用对象包装起来,方便给线程入口函数调用。

------《C++新经典》读书笔记

相关推荐
明月醉窗台2 分钟前
Qt 入门 6 之布局管理
c语言·开发语言·c++·qt
碎梦归途6 分钟前
23种设计模式-结构型模式之适配器模式(Java版本)
java·开发语言·jvm·单例模式·设计模式·适配器模式
云小逸18 分钟前
【C++】继承
开发语言·c++
风静雪冷25 分钟前
Ubuntu中选择Python虚拟环境
开发语言·python
努力学习的小廉42 分钟前
【C++】 —— 笔试刷题day_21
开发语言·c++·算法
YuforiaCode43 分钟前
第十四届蓝桥杯 2023 C/C++组 冶炼金属
c语言·c++·蓝桥杯
kadog1 小时前
《Python3网络爬虫开发实战(第二版)》配套案例 spa6
开发语言·javascript·爬虫·python
徒慕风流1 小时前
利用Python爬虫实现百度图片搜索的PNG图片下载
开发语言·爬虫·python
钢铁男儿1 小时前
C# 实战_RichTextBox选中某一行条目高亮,离开恢复
开发语言·c#
依旧阳光的老码农1 小时前
Windows下使用 VS Code + g++ 开发 Qt GUI 项目的完整指南
开发语言·windows·qt