58 C++ 多线程 解决future只能取得一次结果的问题。--shared_future解决方案。

一 前提:future.get()方法只能获得一次

前面我们学习了使用async 启动异步任务,返回值使用 future<T> 获取的方案。

前面我们也学习了使用 promise<T> pro, 然后通过 pro.setvalue(tempvalue),最后通过 pro.getfuture()得到future。

然后呢,我们就可以通过future.get()去获得里面存储的数据。

但是这个future.get()只能获取一次,原理是内部实现是通过move来实现的。

假设我们的需求是需要获取多次,应该怎么做呢?

C++提供了shared_future

二 shared_future

1.方案一 , async 线程启动后,结果通过 shared_future直接接受。

2.方案二,async 线程启动后,结果通过 future接受后,转化成 shared_future。

//该方法,返回值是double,参数是string,在函数内部可以给一个 int赋值。赋值后的数据可以通过 resultint的实参.getfuture()获得
double promisefunc180(promise<int> &resultint, string strsource) {
	cout << "promisefunc180 start " << endl;
	// 计算完毕后,我们假设计算结果是1000,给resultint赋值
	resultint.set_value(1000);
	cout << "promisefunc180 end " << endl;
	return 3.14;
}

//
void main(){
	//方案一,async 线程启动后,结果通过 shared_future直接接受。
	string str3 = "chinabank";
	promise<int> promi3;
	//注意,这里ayync的返回值是线程入口启动函数的返回值是double, 
	//promi3.get_future()的返回值是线程中想要赋值的数据的返回值
	shared_future<double> fu6 = async(launch::async, promisefunc180, ref(promi3), ref(str3));
	shared_future<int> fu7 = promi3.get_future();
	cout << fu6.get() << endl;;
	cout << fu6.get() << endl;;
	cout << fu6.get() << endl;;
	cout << fu6.get() << endl;;
	cout << fu7.get() << endl;;
	cout << fu7.get() << endl;;
	cout << fu7.get() << endl;;
	cout << fu7.get() << endl;;
	cout << "    0000000000000         "<<endl;
	//方案二,async 线程启动后,结果通过 future接受后,转化成 shared_future。

	//promi3只能使用一次,C++11 文档明确有说明,下面不要复用,否则有runtime exception
	string str4 = "chinabank";
	promise<int> promi4;
	//future<double> fu8 = async(launch::async, promisefunc180, ref(promi3), ref(str4));//runtime exception
	future<double> fu8 = async(launch::async, promisefunc180, ref(promi4), ref(str4));//runtime exception

	shared_future<double> fu9(move(fu8));
	cout << fu9.get() << endl;;
	cout << fu9.get() << endl;;
	cout << fu9.get() << endl;;
	cout << fu9.get() << endl;;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值