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

C++中的异步调用可以使用std::async函数来实现。std::async函数返回一个std::future对象,该对象可以用于获取异步操作的结果。std::async函数有两个参数,第一个参数是std::launch枚举类型,用于指定异步操作的启动方式,可以是std::launch::async表示异步启动,也可以是std::launch::deferred表示延迟启动;第二个参数是一个可调用对象,可以是函数指针、函数对象或者Lambda表达式等。当使用std::launch::async启动异步操作时,std::async函数会在新线程中执行该可调用对象;当使用std::launch::deferred启动异步操作时,std::async函数会在调用get()函数时执行该可调用对象。 下面是一个示例程序,展示了std::async函数的使用方法和异步启动和延迟启动的区别: ``` #include <chrono> #include <future> #include <iostream> int main() { auto begin = std::chrono::system_clock::now(); auto asyncLazy = std::async(std::launch::deferred, [] { return std::chrono::system_clock::now(); }); auto asyncEager = std::async(std::launch::async, [] { return std::chrono::system_clock::now(); }); std::this_thread::sleep_for(std::chrono::seconds(1)); auto lazyStart = asyncLazy.get() - begin; auto eagerStart = asyncEager.get() - begin; auto lazyDuration = std::chrono::duration<double>(lazyStart).count(); auto eagerDuration = std::chrono::duration<double>(eagerStart).count(); std::cout << "asyncLazy evaluated after : " << lazyDuration << " seconds." << std::endl; std::cout << "asyncEager evaluated after: " << eagerDuration << " seconds." << std::endl; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值