std::async

std::async是用来异步的执行一个任务(通过一个函数)。

它的声明如下:

unspecified policy (1)	

template <class Fn, class... Args>
  future<typename result_of<Fn(Args...)>::type>
    async (Fn&& fn, Args&&... args);

specific policy (2)	

template <class Fn, class... Args>
  future<typename result_of<Fn(Args...)>::type>
    async (launch policy, Fn&& fn, Args&&... args);

第二个要传一个启动策略,第一个不用传,默认用 launch::async|launch::deferred

函数参数的含义可以参考:

https://www.cplusplus.com/reference/future/async/

 

先看一个例子:

#include <iostream>       // std::cout
#include <future>         // std::async, std::future

#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)

// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
  sleep(4);
  std::cout << "Thread ID " << gettid() << ": Calculating. Please, wait...\n";
  for (int i=2; i<x; ++i) if (x%i==0) return false;
  return true;
}

int main ()
{
  // call is_prime(313222313) asynchronously:
  std::future<bool> fut = std::async ( std::launch::async, is_prime,313222313);

  std::cout << "Thread ID " << gettid() << ": Checking whether 313222313 is prime.\n";
  bool ret = fut.get();      // waits for is_prime to return
  // ...


  if (ret) std::cout << "It is prime!\n";
  else std::cout << "It is not prime.\n";

  return 0;
}

执行结果:

Thread ID 28440: Checking whether 313222313 is prime.
Thread ID 28441: Calculating. Please, wait...
It is prime!

可以看到,其实是起了一个线程来执行异步任务。

现在我们稍微改一下main函数代码:
 

int main ()
{
  // call is_prime(313222313) asynchronously:
  /*std::future<bool> fut = */std::async ( std::launch::async, is_prime,313222313);

  std::cout << "Thread ID " << gettid() << ": Checking whether 313222313 is prime.\n";
//  bool ret = fut.get();      // waits for is_prime to return
  // ...


  //if (ret) std::cout << "It is prime!\n";
  //else std::cout << "It is not prime.\n";

  return 0;
}

输出:

Thread ID 17736: Calculating. Please, wait...
Thread ID 17735: Checking whether 313222313 is prime.

可以看到这个时候,先执行子线程,子线程结束后继续执行主线程。

这是因为std::async返回的是一个std::future 对象, 它的析构函数会一直阻塞直到std::sync启动的线程结束。

上面的代码,没有保存std::async返回的std::future 对象,所以它是一个临时对象,std::async返回就结束,所以返回即调用 析构函数,析构函数阻塞直到线程结束。

所以会出现上面主线程等待子线程完成的打印。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值