C++线程学习二(future成员函数)

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;
}  

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值