C++11多線程(八):future用法詳解

         C++ 11多線程不能直接從thread.join()獲得想要的結果,必須定義一個變量,在線程執行時對這個變量賦值,然後執行join(), 過程比較複雜。

         std::future可以從異步任務中獲取結果,一般與std::async配合使用,std:async用於創建異步任務,實際上就是創建一個線程執行相應任務,然後std::future對象調用get獲取該值(通常在另一個線程中獲取)。

        使用 std::funture類時需要包含如下頭文件

#include <future>
using namespace std;

std::future構造函數

std::future的拷貝構造函數是被禁用的,只提供默認的構造函數,普通賦值操作也被禁用,只提供了move賦值操作。

future(const future&) = delete;   //拷貝禁用
future& operator=(const future&) = delete;  //賦值禁用

使用方法如下:

std::future<int>  fut;	  //默認構造函數
fut = std::async(do_some_task);   // move賦值操作

async聲明

template<class _Fty, class... _ArgTypes> 
inline future<typename result_of<typename enable_if<!_Is_launch_type<typename decay<_Fty>::type>::value, _Fty>::type(_ArgTypes...)>::type>
	async(_Fty&& _Fnarg, _ArgTypes&&... _Args)
	{	// return a future object whose associated asynchronous state
		// manages a function object
	return (_Async(launch::async | launch::deferred,
		_Decay_copy(_STD forward<_Fty>(_Fnarg)),
		_Decay_copy(_STD forward<_ArgTypes>(_Args))...));
	}

參數1:任務函數

參數2:參數列表,可以是多個參數

返回future對象

 

get返回任務值,聲明如下

_Ty get()
		{	// block until ready then return the stored result or
			// throw the stored exception
		return (_STD move(this->_Get_value()));
		}

 

代碼演示

#include<iostream>
#include<future>
#include<thread>

using namespace  std;
using namespace  std::this_thread;
using namespace  std::chrono;

//費時的操作
int  work(int  a, int  b)
{
	cout << "開始計算:" << endl; 
	sleep_for(seconds(3));  //假設計算耗時3秒
	return  a + b; 
}

int  main()
{
	//將來的結果
	future<int> result = async(work, 123, 456);  //move賦值操作

	result.wait(); //等待結果算出,算出後纔會繼續執行
	cout << "算出結果:" << endl;
	int  sum = result.get();//獲取結果
	cout << "最終的結果是:" << sum << endl;

	system("pause");
	return 0;
}

運行結果:

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