zoukankan      html  css  js  c++  java
  • boost-同步-futures

    概述


    创建异步值


    使用boost::promise或boost::packagedd_task可以设置future的值

    经常有人问:“怎么从线程返回一个值?”,这就是答案:将要运行的函数包装在boost::packaged_task,并传入线程的构造函数

    int calculate_the_answer_to_life_the_universe_and_everything()
    {
        return 42;
    }
    
    boost::packaged_task<int> pt(calculate_the_answer_to_life_the_universe_and_everything);
    boost:: future<int> fi=pt.get_future();
    
    boost::thread task(boost::move(pt)); // launch task on a thread
    
    fi.wait(); // wait for it to finish
    
    assert(fi.is_ready());
    assert(fi.has_value());
    assert(!fi.has_exception());
    assert(fi.get_state()==boost::future_state::ready);
    assert(fi.get()==42);

    boost::promise稍底层:它提供函数来将值或异常存到对应的future。

    因此值可能有多个来源或一个操作可能产生多个结果时,适合用boost::promise

    boost::promise<int> pi;
    boost:: future<int> fi;
    fi=pi.get_future();
    
    pi.set_value(42);
    
    assert(fi.is_ready());
    assert(fi.has_value());
    assert(!fi.has_exception());
    assert(fi.get_state()==boost::future_state::ready);
    assert(fi.get()==42);

    wait callbacks and lazy futures


    promise和packaged_task都支持wait callbacks

    使用成员函数set_wait_callback()来设置

    这个方法产生了lazy futures,即只有在需要的时候才会计算结果。在下面的例子中,只有运行f.get()才会调用nvoke_lazy_task

    int calculate_the_answer_to_life_the_universe_and_everything()
    {
        return 42;
    }
    
    void invoke_lazy_task(boost::packaged_task<int>& task)
    {
        try
        {
            task();
        }
        catch(boost::task_already_started&)
        {}
    }
    
    int main()
    {
        boost::packaged_task<int> task(calculate_the_answer_to_life_the_universe_and_everything);
        task.set_wait_callback(invoke_lazy_task);
        boost:: future<int> f(task.get_future());
    
        assert(f.get()==42);
    }

    处理分离的线程以及线程专用变量


    ……

  • 相关阅读:
    Oracle数据库限定特定用户 特定IP 登录
    Elasticsearch 监控
    Elasticsearch 使用:创建、插入、查询、更新、删除
    ES 的基本用法
    elasticsearch 集群管理(集群规划、集群搭建、集群管理)
    ElasticSearch 集群环境搭建,安装ElasticSearch-head插件,安装错误解决
    Greenplum 基准测试
    MySQL 计算时间差函数 TIMESTAMPDIFF、DATEDIFF
    PostgreSQL 时间函数 extract函数
    Greenplum最佳实践
  • 原文地址:https://www.cnblogs.com/sqxy110/p/5250850.html
Copyright © 2011-2022 走看看