std::async异步编程

这篇博客演示了C++中使用`std::async`创建异步线程并同步获取结果的过程。主要内容包括在线程间传递数据、异步执行函数`func`以及主线程与子线程的并发执行。通过示例代码展示了如何在主线程中等待子线程完成并获取返回值。
摘要由CSDN通过智能技术生成

传入线程函数

eg:

#include <iostream>
#include <string.h>
#include <thread>
#include <future>

using namespace std;

int func(int user_data)
{
    cout << "child thread start, id is " << std::this_thread::get_id() << endl;
    for(int i = 0; i < 10; ++i)
    {
        cout << "i = " << i << endl;
        std::this_thread::sleep_for(1s);
    }
    cout << "child thread exit, id is " << std::this_thread::get_id() << endl;
    return user_data + 1;
}

int main()
{
    cout << "main thread start, id is " << std::this_thread::get_id() << endl;

    future<int> ft = async(std::launch::async, func, 998);
    for(int j = 0; j < 5; ++j)
    {
        cout << "j = " << j << endl;
        std::this_thread::sleep_for(1s);
    }
    cout << "main thread end, id is " << std::this_thread::get_id() << endl;
    cout << "child thread return is " << ft.get() << endl; // 会一直阻塞到子线程返回
    system("pause");
    return 0;
}

结果如下所示:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值