C++11>future,promise

future可以通過特殊的provider進行數據的異步訪問,實現線程間的通信


// promise example
#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int(std::future<int>& fut) {
	int x = fut.get();
	std::cout << "value: " << x << '\n';
	std::system("pause");
}

int main()
{
	std::promise<int> prom;                      // create promise     #創建promise
	std::future<int> fut = prom.get_future();    // engagement with future #與future綁定
	std::thread th1(print_int, std::ref(fut));  // send future to new thread  #將future傳入promise
	prom.set_value(10);                         // fulfill promise  #執行promise
												// (synchronizes with getting the future) 
	th1.join();
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章