c++多线程 五 ---(future/promise 模型)

这个代码很简单不太详细讲解,future/promise 模型 想象成为线程间传递结果的通信信道。

#include <future>
int calculate()
{
	return 123;
}

void testcalculate()
{
	auto fut = async(calculate);
	//auto fut = async(launch::async ,calculate); //创建一个线程
	//auto fut = async(launch::deferred,calculate);//使用的当前
	int res = fut.get();
	cout << "the answer is " << res << endl;
}

 结果:

the answer is 123

另一个例子:

#include <future>
#include <list>
#include <iostream>
#include <exception>

using namespace std;


thread::id func()
{
	return this_thread::get_id();
}

int main()
{
	cout << "starting 2 tasks" << endl;
	cout << "- task1: process endless loop of memory consumption" << endl;
	cout << "- task2: wait for <return> and then for task1" << endl;
	auto f1 = async(func); // start task1() asynchronously (now or later or never)
						   //返回一个future<thread::id>对象  //async有两种启动策略  一是马上异步执行 launch::async   一是延迟到调用get 函数才异步执行   launch::deferred

	cout << "\nwait for the end of task1: " << endl;
	try
	{
		cout << f1.get(); //wait for task1() to finish (raises exception ifany)
						  //acquire the result
	}
	catch (const exception& e)
	{
		cerr << "EXCEPTION: " << e.what() << endl;
	}
	cin.get();

	getchar();

    return 0;
}

结果:

starting 2 tasks
- task1: process endless loop of memory consumption
- task2: wait for <return> and then for task1

wait for the end of task1:
7396

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值