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()