STL:并发一之 async() and future class

async,中文意思为异步,async()提供的借口让一个可调用对象在后台运行,成为一个独立的线程;
它将其获得的函数立即异步启动于一个分离的线程;

future<>是一个模板类,等待线程结果并获取结果,这个结果不是我们立刻需要知道的,有可能过一会才会用到,所以叫future。这个结果可能是返回值,也可能是一个异常; future为async被调用的返回类型的特化,我们需要调用它,这是因为:它可以确保async的被调用对象的执行。使用get()获取异步线程的结果。如果没调用get(),并不能保证async的函数被执行。如果不调用get(),主线程也不会等待异步线程,可能导致主线程提前结束。

需要注意的是,这只适用于不发生数据竞争的情况。

简单地说,使用只需要:

1 包含 #include <future>头文件
2 std::future<Return type> result(std::async(callable object); )
3 result.get();

够简单!

下面看一个来自《C++标准库 第二版》中的例子;

#include <future>
#include <thread>
#include <chrono>
#include <random>
#include <iostream>
#include <exception>
using namespace std;

int doSomething(char c)
{
	// random-number generator (use c as seed to get different sequences)
	std::default_random_engine dre(c);
	std::uniform_int_distribution<int> id(10, 1000);

	// loop to print character after a random period of time
	for (int i = 0; i<10; ++i) {
		this_thread::sleep_for(chrono::milliseconds(id(dre)));
		cout.put(c).flush();
	}

	return c;
}

int func1()
{
	return doSomething('.');
}

int func2()
{
	return doSomething('+');
}

int main()
{
	std::cout << "starting func1() in background"
		<< " and func2() in foreground:" << std::endl;

	// start func1() asynchronously (now or later or never):
	//std::future<int> result1(std::async(func1));
	auto  result1(std::async(func1));
	int result2 = func2();    // call func2() synchronously (here and now)

							  // print result (wait for func1() to finish and add its result to result2
	int result = result1.get() + result2;

	std::cout << "\nresult of func1()+func2(): " << result
		<< std::endl;

	system("pause");
	return 0;
}

由上可知,async后,线程可能不是异步的。我们可以采用launch策略,让线程以异步的方式执行。

launch是一个枚举类,

enum class launch {	// names for launch options passed to async
	async = 0x1,
	deferred = 0x2
	};

采用std::launch::async 策略后,如果异步无法实现,就会throw std::system_error的异常。

采用std::launch::deferred 后,只要调用get()的时候,线程才会启动。

使用try catch获取异常,例如:

try {
f1.get()
}
cathch(const exception&e)
{
	...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值