前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++11 std::async

C++11 std::async

原创
作者头像
awk
发布2018-08-23 16:52:49
4530
发布2018-08-23 16:52:49
举报
文章被收录于专栏:cpp
代码语言:c++
复制

//g++ -std=c++11 -pthread -g std_future.cpp -o main
// async example
#include <iostream>       // std::cout
#include <future>         // std::async, std::future

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

int main ()
{
  long int x3=2147483647;
  long int x2=623222313;
  long int x1=444444443;
  // call is_prime(313222313) asynchronously:
  std::cout << "Start Checking whether " << x1 << " is prime.\n";
  std::future<bool> fut1 = std::async (std::launch::async, is_prime,x1);
  
  std::cout << "Start Checking whether " << x2 << " is prime.\n";
  std::future<bool> fut2 = std::async (std::launch::async, is_prime,x2);
  
  std::cout << "Start Checking whether " << x3 << " is prime.\n";
  std::future<bool> fut3 = std::async (std::launch::async, is_prime,x3);


  std::cout << x1 << (fut1.get() ? " is prime\n" : " is not prime\n");

  std::cout << x2 << (fut2.get() ? " is prime\n" : " is not prime\n");
  
  std::cout << x3 << (fut3.get() ? " is prime\n" : " is not prime\n");
  
  return 0;
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档