C++并发与多线程笔记八:async、future、packaged_task、promise

本文详细介绍了C++中std::async、std::future、std::packaged_task和std::promise的用法,包括如何创建后台任务并返回值,异步任务的启动方式,以及std::promise在线程间传递数据的应用。重点讨论了std::launch策略对任务执行的影响,以及std::packaged_task的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 前言

本文接上文 C++并发与多线程笔记七:condition_variable、wait、notify_one/all 的内容,主要记录 async、future、packaged_task、promise 概念以及用法。

2 std::async、std::future 创建后台任务并返回值

2.1 基本用法

std::async 是个函数模板,用来启动一个异步任务,启动一个异步任务后,它返回一个 std::future 类模板对象。

上述"启动一个异步任务"的本质含义就是自动创建一个线程并开始执行对应的线程入口函数,它返回一个 std::future 类模板对象,这个对象内就含有线程入口函数的返回值(即线程执行的返回结果)。

我们可以通过调用 std::future 对象的成员函数 get() 来获取结果。即 std::future 提供了一种访问异步操作结果的机制,就是说这个结果可能没办法马上拿到,在线程执行完毕后,才能拿到。

注:std::future 对象里会保存一个值,在将来的某个时刻能够拿到。

在下面的示例代码中,std::future 对象的 get() 成员函数等待线程结束并返回结果,也就是说 get() 函数在拿不到值时是阻塞的。另外,std::future 对象还有个 wait() 成员函数,等待线程返回,但函数本身并不返回结果,类似线程对象中的 join() 函数。

#include <thread>
#include <future> /* 需要包含该头文件 */
#include <iostream>
using namespace std;

/* 线程入口函数 */
int myThread() {
   
  cout << "myThread() start thread ID = " << std::this_thread::get_id() << endl;
  std::chrono::milliseconds duration(5000); /* 定义间隔时间为 5000 ms */
  std::this_thread::sleep_for(duration);    /* 睡眠指定的间 */
  cout << "myThread() end thread ID = " << std::this_thread::get_id() << endl;
  return 5;
}

int main() {
   
  cout << "main() start thread ID = " << std::this_thread::get_id() << endl;

  /* 定义一个std::future类模板对象,变量类型为 int, */
  /* 并通过 std::async 启动一个异步任务 myThread */
  std::future<int> result = std::async(myThread);

  cout << "continue......!" << endl;

  /* get() 函数会阻塞在这,等待 myThread 线程执行完毕后返回  */
  cout << result.get() << endl;
  // result.wait(); /* 等待线程执行完毕,但不返回值 */

  cout << "main() end thread ID = " << std::this_thread::get_id() << endl;
  return 0;
}

输出结果:

main() start thread ID = 1860
continue......!
myThread() start thread ID = 3300
# 这里会阻塞 5000 ms
myThread() end thread ID = 3300
5
main() end thread ID = 1860

注:std::future 对象的 get() 成员函数只能调用一次,否则运行时会发生异常:std::future_error

使用类成员函数作为 std::async 启动的线程回调函数有些额外的细节,示例代码如下,具体详见注释:

#include <thread>
#include <future> /* 需要包含该头文件 */
#include <iostream>
using namespace std;

class A {
   
 public:
  /* 线程入口函数 */
  int myThread(int myParameter) {
   
    cout << myParameter << endl;
    cout << "myThread() start thread ID = " << std::this_thread::get_id() << endl;
    std::chrono::milliseconds duration(5000); /* 定义间隔时间为 5000 ms */
    std::this_thread::sleep_for(duration);    /* 睡眠指定的间 */
    cout << "myThread() end thread ID = " << std::this_thread::get_id() << endl;
    return 5;
  }
};

int main() {
   
  A objA;
  int tempParameter = 12;
  cout << "main() start thread ID = " << std::this_thread::get_id() 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值