同过future和promise来实现线程间的通信,不需要使用互斥量和条件变量等。
promise(承诺)<------> future(未来)
有承诺才有未来,承诺做为一个参数,承诺的东西做完之后,才会有未来。
示例如下:
#include
#include
using namespace std;
void add_func(promise& mypromise, int x, int y);
int main(void)
{
promise pm;
//定义了一个promise对象,对象接收的类型是int
future future;
//代表接收的类型是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& 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
#include
using namespace std;
void thread1(promise& mypromise, int n);
void thread2(future& myfuture);
int main(void)
{
promise pm;
future 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& 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& myfuture)
{
int m = myfuture.get();
cout << "m = " << m << endl;
}