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++后台服务器开发