future(promise,async) c++11异步库,线程的代替品

本文介绍了C++11异步库的使用,特别是future、promise和async的功能。future作为线程的代替品,简化了数据同步交互的复杂性。示例展示了如何使用async启动异步任务,并通过future获取结果,简化了传统的线程同步操作。同时提到了shared_future,它允许多次获取结果,进一步说明了异步库如何优雅地处理多线程竞争问题。

线程执行需要自己建线程,这个还好,但是如果有数据同步交互就麻烦点。比如常见的需求,线程异步执行下面这个耗时的函数,方法返回int传给主线程,主线程在未来某一步需要结果的时候等待,还要用condition_variable来阻塞等待。异步库并没有什么比较trick的东西,更像是语法糖,把线程常用的东西简单化。


int test(int a){

for (int i = 0; i < 10;i++){
this_thread::sleep_for(chrono::milliseconds(1000));//代替某些耗时方法
cout << ++a<<endl;
}
return a;
}


1.单纯用async和future

#include <future>         // std::promise, std::future

int main(void)
{
future<int> ft = async(test,100);

this_thread::sleep_for(chrono::milliseconds(3000));
cout << "waiting result" << endl;
cout << "get result:"<<ft.get()<<endl;//阻塞等待结果,就两句话完成线程同步工作

getchar();
return 0;
}


2.shared_future 可以重复get的future。下面的例子吧多线程race更改为future完成的

#include <thread>
#include <future>  

class TestThread
{
public:
	TestThread(shared_future<bool> & sf) :sfuture(sf){}

	void start(){ 
		thread t(std::bind(&TestThread::run,this));
		t.detach();
	}

	void run(){
			cout << "test thread waits. id:" << std::this_thread::get_id()<<endl;
			bool flg=sfuture.get();
			cout << "test thread is racing:" << std::this_thread::get_id() << endl;
	}

	shared_future<bool> &sfuture;
};



int main(void)
{
	cout << "main thread id:" << std::this_thread::get_id() << endl;
	
	promise<bool> prom;
	future<bool> ft=prom.get_future();
	shared_future<bool> & sfuture = ft.share();

	for (int i = 0; i < 10; i++){
		TestThread testThread(sfuture);
		testThread.start();
	}

	cout << "ready?" << endl;
	this_thread::sleep_for(chrono::milliseconds(3000));
	cout << "go!" << endl;
	prom.set_value(true);

	getchar();
	return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值