promise的创建

        同过future和promise来实现线程间的通信,不需要使用互斥量和条件变量等。

        promise(承诺)<------> future(未来)

        有承诺才有未来,承诺做为一个参数,承诺的东西做完之后,才会有未来。

        示例如下:

#include<iostream>
#include<future>


using namespace std;
void add_func(promise<int>& mypromise, int x, int y);
int main(void)
{
	promise<int> pm;
	//定义了一个promise对象,对象接收的类型是int
	future<int> future;
	//<int>代表接收的类型是int
	future = pm.get_future();
	//让promise和future之间产生关联
	thread t(add_func,ref(pm),10,20);

	int sum = future.get();//等待子线程结束,本身是一个阻塞的函数
	cout << "sum = " << sum << endl;
	t.join();
	return 0;
}

void add_func(promise<int>& mypromise, int x, int y)
{
	cout << "x = " << x << " y = " << y << endl;
	int sum = 0;
	sum = x + y;
	this_thread::sleep_for(chrono::seconds(5));
	mypromise.set_value(sum);//放置运行出来的结果
}

        promise像是一个容器,来承接参数。

        以上是介绍了主线程与子线程之间的通信,下面介绍子线程与子线程之间的通信。

如下:不难理解,读者自行阅读:

#include<iostream>
#include<future>

using namespace std;
void thread1(promise<int>& mypromise, int n);
void thread2(future<int>& myfuture);
int main(void)
{
	promise<int> pm;
	future<int> future;
	future = pm.get_future();
	thread t1(thread1, ref(pm),5);
	thread t2(thread2, ref(future));
	t1.join();
	t2.join();
	return 0;
}
void thread1(promise<int>& mypromise, int n)
{
	cout << "thread1 input value: " << n << endl;
	n *= 100;
	this_thread::sleep_for(chrono::seconds(5));
	mypromise.set_value(n);
}

void thread2(future<int>& myfuture)
{
	int m = myfuture.get();
	cout << "m = " << m << endl;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值