zoukankan      html  css  js  c++  java
  • C++11中async中future用法(一)

    async意味着异步执行代码,看如下示例:

    #include <future>
    #include <thread>
    #include <chrono>
    #include <random>
    #include <iostream>
    #include <exception>
    
    using namespace std;
    
    int do_something(char c)
    {
        std::default_random_engine dre(c);
        std::uniform_int_distribution<int> id(10, 1000);
    
        for (int i = 0; i < 10; ++i)
        {
            this_thread::sleep_for(chrono::microseconds(id(dre)));
            cout << c << ends;
        }
    
        return c;
    }
    
    
    
    int main() {
        cout << "begin ..." << endl;
        std::future<int> result = std::async(do_something, 'c');
        cout << "waiting for result ..." << endl;
        cout << "
    " << result.get() << endl;
        cout << "finish!" << endl;
    }

    当对result调用get时,如果此时do_something函数还没有执行完毕,那么会导致main函数阻塞在这里,一直到该函数执行完毕。

    async返回的是一个future对象,从字段意思上推测,结果是在未来的某一个时刻拿到。

    async实际上是在背后偷偷的开启一个线程执行函数,但是上面的实例看不出来,于是我们写一个复杂一些的实例:

    #include <future>
    #include <thread>
    #include <chrono>
    #include <random>
    #include <iostream>
    #include <exception>
    
    using namespace std;
    
    
    int do_something(char c)
    {
        std::default_random_engine dre(c);
        std::uniform_int_distribution<int> id(10, 1000);
    
        for (int i = 0; i < 10; ++i)
        {
            this_thread::sleep_for(chrono::microseconds(id(dre)));
            cout << c << ends;
        }
    
        return c;
    }
    
    
    int func1()
    {
        return do_something('.');
    }
    
    int func2()
    {
        return do_something('*');
    }
    
    
    int main()
    {
        cout << "start ..." << endl;
        // std::future<int> result1(std::async(std::launch::deferred, func1));
        std::future<int> result1(std::async(func1));
    
        int result2 = func2();
    
        int result = result1.get() + result2;
    
        cout << "
    result of func1() + func2(): " << result << endl;
    }

    这个程序的执行结果中 .和*乱序出现,说明func1和func2是乱序执行的,这是因为func1是在另一个线程中执行的。

  • 相关阅读:
    Django之搭建学员管理系统
    数据库查询操作(fetchone,fetchall)
    HTTP 方法:GET与 POST
    初识django框架
    Memcached的批量删除方案总结
    centos5.5 下面 lnmp环境遇到的小问题
    CentOS 5.5 --学习(1)
    HTTP请求方法及响应码详解(http get post head)
    codeigniter注意点
    htaccess 伪静态的规则
  • 原文地址:https://www.cnblogs.com/inevermore/p/5092667.html
Copyright © 2011-2022 走看看