0
点赞
收藏
分享

微信扫一扫

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

沪钢木子 2022-04-13 阅读 68
c++

一、作用:
异步一个线程,执行用户传入的函数。其封装了创建销毁线程过程,用户不感知。通过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 条评论