C++11新特性之 std::future and std::async

原文转载于:https://blog.csdn.net/wangshubo1989/article/details/49872199

std::future

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

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

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

std::thread t([]() { auto res = perform_long_computation(); });

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

MyResult sharedRes;
std::thread t([&]() { sharedRes = perform_long_computation(); });

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

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. 
因此,有了这样的代码:

std::future<MyResult> result = std::async([]() { return perform_long_computation(); });
MyResult finalResult = result.get();

上一段完整的代码:

// 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的原型

async(std::launch::async | std::launch::deferred, f, args...)
  • 1

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

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 << "deferred\n";
    } else if (status == std::future_status::timeout) {
        std::cout << "timeout\n";
    } 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

这里写代码片 
“`


猜你喜欢

转载自blog.csdn.net/business122/article/details/80884050