C++ 多线程(四):std::async

一、作用:
异步一个线程,执行用户传入的函数。其封装了创建销毁线程过程,用户不感知。通过std::future获取异步线程执行完函数返回的结果

1.1、线程创建策略:
std::launch::async调度策略意味着函数必须异步执行,即在另一线程执行。
std::launch::deferred调度策略意味着函数只会在std::async返回的future对象调用get或wait时执行

二、用法:
在主线程中,异步出两个线程完成不同任务。

struct X {   
	int foo(int i, const std::string& str) {  
		std::lock_guard<std::mutex> lk(m);        
		std::cout << str << ' ' << i << '\n';     
		return i + 20; 
	}    
	void bar(const std::string& str) {       
		std::lock_guard<std::mutex> lk(m);   
		std::cout << str << '\n';      
	}  
}; 

int main()  
{    
	X x;   
	// 以 async 策略调用 x.foo(42, "Hello") :  
	// 同时打印 "Hello 42"    
	std::future a1 = std::async(std::launch::async, &X::foo, &x, 42, "Hello");    
	std::cout << a1.get() << '\n'; // 打印 "62"    
	// 以 deferred 策略调用 x.bar("world!")    
	// 调用 a2.get() 或 a2.wait() 时打印 "world!"   
	std::future a2 = std::async(std::launch::deferred, &X::bar, x, "world!");      
	a2.wait();                     // 打印 "world!"  
}      

三、参考链接:
1、cppreference.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值