我是靠谱客的博主 明理月饼,这篇文章主要介绍C++11新特性之 std::future and std::async,现在分享给大家,希望可以做个参考。

先来个小插曲,百度翻译,你够了:
这里写图片描述
std::future

设想这样的情况,你希望一个线程做一些事情,然后返回你一个结果。同时,你在做一些其他的工作,该工作也许会也许不会花费你一点时间。你希望在某个特定的时间获取那个线程的结果。
在win32中,你可以这样
用CreateThread启动线程
在线程里,启动任务,当准备完毕后发送一个事件(event),并把结果放在全局变量里。
在主函数里(main)做其它的事情,然后在你想要结果的地方,调用WaitForSingleObject
在c++11,这个可以轻松被std::future实现,然后返回任何类型,因为它是一个模板。

std::future 究竟是什么呢?简单地说,std::future 可以用来获取异步任务的结果,因此可以把它当成一种简单的线程间同步的手段。

让我们考虑一个简单的事儿:用线程计算一些值:

复制代码
1
std::thread t([]() { auto res = perform_long_computation(); });

std::thread在之前的博客中已经介绍过了。我们还可以更高效吗?

复制代码
1
2
MyResult sharedRes; std::thread t([&]() { sharedRes = perform_long_computation(); });

这个时候,我们应该知道thread什么时候执行结束,这里有一个很简单的方式

复制代码
1
2
auto result = std::async([]() { return perform_long_computation(); }); MyResult finalResult = result.get();

上诉代码很简洁明了吧,我们需要弄清其原理。
英文描述可能更加确切:
std::future holds a shared state
std::async allow us to run the code asynchronously.
因此,有了这样的代码:

复制代码
1
2
std::future<MyResult> result = std::async([]() { return perform_long_computation(); }); MyResult finalResult = result.get();

上一段完整的代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// future example #include <iostream> // std::cout #include <future> // std::async, std::future #include <chrono> // std::chrono::milliseconds // a non-optimized way of checking for prime numbers: bool is_prime (int x) { for (int i=2; i<x; ++i) if (x%i==0) return false; return true; } int main () { // call function asynchronously: std::future<bool> fut = std::async (is_prime,444444443); // do something while waiting for function to set future: std::cout << "checking, please wait"; std::chrono::milliseconds span (100); while (fut.wait_for(span)==std::future_status::timeout) std::cout << '.' << std::flush; bool x = fut.get(); // retrieve return value std::cout << "n444444443 " << (x?"is":"is not") << " prime.n"; return 0; }

输出:
checking, please wait……………………
444444443 is prime.

std::async
为什么要用std::async代替线程的创建

std::async是为了让用户的少费点脑子的,它让这三个对象默契的工作。大概的工作过程是这样的:std::async先将异步操作用std::packaged_task包装起来,然后将异步操作的结果放到std::promise中,这个过程就是创造未来的过程。外面再通过future.get/wait来获取这个未来的结果,怎么样,std::async真的是来帮忙的吧,你不用再想到底该怎么用std::future、std::promise和std::packaged_task了,std::async已经帮你搞定一切了!

现在来看看std::async的原型

复制代码
1
async(std::launch::async | std::launch::deferred, f, args...)

第一个参数是线程的创建策略,有两种策略,默认的策略是立即创建线程:
std::launch::async:在调用async就开始创建线程。
std::launch::deferred:延迟加载方式创建线程。调用async时不创建线程,直到调用了future的get或者wait时才创建线程。
第二个参数是线程函数,第三个参数是线程函数的参数。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
std::future<int> future = std::async(std::launch::async, [](){ std::this_thread::sleep_for(std::chrono::seconds(3)); return 8; }); std::cout << "waiting...n"; std::future_status status; do { status = future.wait_for(std::chrono::seconds(1)); if (status == std::future_status::deferred) { std::cout << "deferredn"; } else if (status == std::future_status::timeout) { std::cout << "timeoutn"; } else if (status == std::future_status::ready) { std::cout << "ready!n"; } } while (status != std::future_status::ready); std::cout << "result is " << future.get() << 'n';

可能的结果:
waiting…
timeout
timeout
ready!
result is 8

这里写代码片
“`

最后

以上就是明理月饼最近收集整理的关于C++11新特性之 std::future and std::async的全部内容,更多相关C++11新特性之内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部