1、future成员函数介绍与使用示例
示例一:future的成员函数与基本使用
Member()函数后面会有定义与声明,目前只是介绍future的使用
cout << "main thread ID " << this_thread::get_id() << endl;
std::future<int> res = std::async(MemberFun,1); // 创建一个线程开始执行
cout << "continue ... " << endl;
//cout << res.get() << endl; // 卡在这里等待threasIO执行完
// res.wait();
std::future_status status = res.wait_for(std::chrono::seconds(6));
if (status == std::future_status::timeout) // 线程超时
{
// 超时表示线程没有执行完
cout << "运行超时,线程未执行完" << endl;
}
else if (status == std::future_status::ready) // 成功返回
{
cout << "线程成功返回" << endl;
cout << res.get() << endl;
}
else if (status == std::future_status::deferred) // 线程延迟执行,
{
// 需要将std::async第一个参数设置deferred,需要get()函数才能让线程执行
// std::future<int> res = std::async(std::launch::deferred, MemberFun, 1); // 延迟示例
cout << "线程延迟执行" << endl;
cout << res.get() << endl;
}
示例二:shared_future 使用范例 一
std::future<int> ful = tPromise.get_future(); // 拿到上一个线程的
//std::shared_future<int> resShare(std::move(ful));
//std::shared_future<int> resShare(ful.share()); // 两种方式都可以
bool fulValue = ful.valid(); // 判断ful是否有有效值
std::shared_future<int> fulShare(ful.share());
fulValue = ful.valid();
auto threadRes = fulShare.get();
std::thread t1(proThread, std::ref(ful));// get()不能重复调用,在proThread()函数中有调用
t1.join();
示例三:shared_future 使用范例 二
std::shared_future<int> ful(tPromise.get_future()); // 通过get_future返回值,构造一个get_future对象
auto threadRes = ful.get();
cout << "threadRes " << threadRes << endl;
cout << "end" << endl;
示例四:整体介绍
#include <iostream>
#include <thread>
#include <mutex>
#include <future>
using namespace std;
int MemberFun(int num)
{
cout << "input thread param " << num << endl;
cout << "start this thread ID " << std::this_thread::get_id() << endl;
std::chrono::milliseconds dura(5000);
std::this_thread::sleep_for(dura);
cout << "end this thread ID " << std::this_thread::get_id() << endl;
return 5;
}
void promiseThread(std::promise<int> &temp, int num)
{
num += 10;
int res = num;
temp.set_value(res); // 将结果保存到temp对象中
}
void proThread(std::shared_future<int> &temp)
{
auto res = temp.get();
//auto res1 = temp.get();
cout << "proThread res: " << res << endl;
return;
}
int main()
{
// std::ref 用于包装按引用传递的值。
// std::cref 用于包装按const引用传递的值。
std::promise<int> tPromise; // 生命promise对象,保存类型为int
std::thread t(promiseThread, std::ref(tPromise), 180);
t.join();
// shared_future使用范例 二
std::shared_future<int> ful(tPromise.get_future());
auto threadRes = ful.get();
cout << "threadRes " << threadRes << endl;
cout << "end" << endl;
system("pause");
return 0;
}