C++多线程编程(第四章 promise和future)

promise 和future

promise用于异步传输变量

std::promise提供存储异步通信的值,再通过其对象创建的std::future异步获得结果。
std::promise只能使用一次。void set_value(_Ty&& _Val)设置传递值,只能调用一次

std::future提供访问异步操作结果的机制

get()阻塞等待promise set_value的值

代码演示

/*
C++ 11
promise与future


*/

#include 
#include 
#include 
#include 

using namespace std;


void TestFuture(promise<string>p)
{
	this_thread::sleep_for(3s);
	cout << "Begin set value" << endl;
	p.set_value("TestFuture value");
	this_thread::sleep_for(3s);
	cout << "end TestFutrue" << endl;
}

int main()
{
	//异步传输变量存储
	promise<string>p;

	//用来获取线程异步值获取
	auto future = p.get_future();

	auto th = thread(TestFuture, move(p));
	cout << "begin future.get()" << endl;
	cout << "future_get() = " << future.get() << endl;
	cout << "end future.get()" << endl;
	th.join();

	//getchar();
	printf("All done!\n");
	return 0;
}

C++多线程编程(第四章 promise和future)_第1张图片

你可能感兴趣的:(C++,多线程,笔记心得,c++,java,jvm)