C++11異步 async

C++11異步 async


一、簡介

**std::async()**是一個接受回調(函數或函數對象)作爲參數的函數模板,並有可能異步執行它們.

函數原型:

template<class Fn, class... Args>
future<typename result_of<Fn(Args...)>::type> async(launch policy, Fn&& fn, Args&&...args);

函數說明:

std::async返回一個,它存儲由執行的函數對象返回的值。

函數期望的參數可以作爲函數指針參數後面的參數傳遞給std::async()。

參數說明:

std::async中的第一個參數是啓動策略,它控制std::async的異步行爲,我們可以用三種不同的啓動策略來創建std::async
·std::launch::async
保證異步行爲,即傳遞函數將在單獨的線程中執行
·std::launch::deferred
當其他線程調用get()來訪問共享狀態時,將調用非異步行爲
·std::launch::async | std::launch::deferred
默認行爲。有了這個啓動策略,它可以異步運行或不運行,這取決於系統的負載,但我們無法控制它。


二、案例

#include <iostream>
#include <future>
#include <string>
#include <windows.h>

using namespace std;
void fun1()
{
	Sleep(500);
	std::cout << "fun1..." << std:: endl;
}

void fun2(int n)
{
	Sleep(100);
	std::cout << "fun2 n:"<<n << std::endl;
}
std::string fun3(const std::string& str)
{
	cout << str << endl;
	return str;
}

void fun5(const string& str)
{
	cout << "hello :"<<str << endl;
}
int main()
{
	auto pfun1 = std::async(fun1);
	auto pfun2 = std::async(fun2,2);
	auto pfun3 = std::async(fun3,"hello async");
	//lambda表達式
	auto pfun4 = std::async([] {
		cout << "pfun4" << endl;
	});
	//綁定函數
	auto pfun5 = std::async(bind(fun5,"bind"));
	//獲取返回值
	cout << "pfun3:"<< pfun3.get()<< endl;
	system("pause");
	return 0;
}

想了解學習更多C++後臺服務器方面的知識,請關注:
微信公衆號:C++後臺服務器開發

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