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);
    }

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


    ……

  • 相关阅读:
    linux 分析 目标文件 的命令
    bss,data,text,rodata,堆,栈,常量段
    Linux进程地址空间详解
    机器周期,指令周期,时钟周期,节拍与晶振
    银行家算法——C语言(11计科1班-孙鹏启——修正)
    bash —— bind ( 一个功能强大的组合键! Alt + . )
    【5002】排版问题
    【?】【7007】栈、模拟
    【u235】背单词
    【t076】竞赛排名
  • 原文地址:https://www.cnblogs.com/sqxy110/p/5250850.html
Copyright © 2011-2022 走看看