• 验证c++11里面的future是否是新开一个线程实现的异步


    开玩笑了,因为在async和future的解释中是写了会新开一个线程去执行任务的。
    那我们在不看源代码的情况下怎么验证这个事?

    源码

    // async example 02.cpp
    #include <iostream>       // std::cout
    #include <future>         // std::async, std::future
    
    // a non-optimized way of checking for prime numbers:
    bool is_prime (int x) {
      std::cout << "Calculating. Please, wait...
    ";
      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 (is_prime,313222313);
    
      std::cout << "Checking whether 313222313 is prime.
    ";
      // ...
    
      bool ret = fut.get();      // waits for is_prime to return
    
      if (ret) std::cout << "It is prime!
    ";
      else std::cout << "It is not prime.
    ";
    
      return 0;
    }
    

    编译运行结果

    看下面编译和执行的结果:

    [root@lh test]# g++ 02.cpp -o 02 -std=c++11
    [root@lh test]# ./02
    Checking whether 313222313 is prime.
    terminate called after throwing an instance of 'std::system_error'
      what():  Unknown error -1
    Aborted (core dumped)
    [root@lh test]# g++ 02.cpp -o 02 -std=c++11 -lpthread
    [root@lh test]# ./02
    Checking whether 313222313 is prime.
    Calculating. Please, wait...
    It is prime!
    

    结论

    从结果中可以看出,当编译的时候不关联lpthread库文件运行时会coredump,反之正常。
    可以说明async、future是单独开线程运行的,同理的还有promise和packaged_task。
    而future中的wait_for也很容易理解,和condition_variable::wait_for是不是很像?
    所以,C++11中的轻量级线程本身还是通过线程实现的,在代码编写中实现了轻量,在性能上可能就不是了。
    因为没有线程池,所以每次执行异步的时候都会创建、析构线程,客户端编程无所谓,服务端编程效率可就不高了。

    引申

    那async是否可以在线程池里来跑呢?答案是可以的,可以参见boost::thread中的synchronization.html。
    不过那不是C++11里的async了,async的原型如下:
    BOOST_THREAD_FUTURE
    async(Executor& ex, R(*f)(BOOST_THREAD_FWD_REF(ArgTypes)...), BOOST_THREAD_FWD_REF(ArgTypes)... args)

    转载请注明来源:https://www.cnblogs.com/bugutian/
  • 相关阅读:
    python从字符串内取两个符号之间的内容
    C# 判读取得字符编码格式
    jquery:字符串(string)转json
    SQL Server 2008 SQL2012 SQL2014 收缩日志 清空删除大日志文件
    WEB 倒计时
    成功配置TOMCAT的LOG4J日志系统,格式:HTML+每天以YYYY-MM-DD.LOG命名的日志文件
    IE Error: '__doPostBack' is undefined 问题解决
    分享:JAVA和C# 3DES加密解密
    好用的linux工具
    python多线程的概念(转载)
  • 原文地址:https://www.cnblogs.com/bugutian/p/14539294.html
Copyright © 2020-2023  润新知