zoukankan      html  css  js  c++  java
  • std::promise

    std::promise code sample:

    #include <vector>
    #include <thread>
    #include <future>
    #include <numeric>
    #include <iostream>
    #include <chrono>
     
    void accumulate(std::vector<int>::iterator first,
                    std::vector<int>::iterator last,
                    std::promise<int> accumulate_promise)
    {
        int sum = std::accumulate(first, last, 0);
        accumulate_promise.set_value(sum);  // Notify future
    }
     
    void do_work(std::promise<void> barrier)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        barrier.set_value();
    }
     
    int main()
    {
        // Demonstrate using promise<int> to transmit a result between threads.
        std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
        std::promise<int> accumulate_promise;
        std::future<int> accumulate_future = accumulate_promise.get_future();
        std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
                                std::move(accumulate_promise));
     
        // future::get() will wait until the future has a valid result and retrieves it.
        // Calling wait() before get() is not needed
        //accumulate_future.wait();  // wait for result
        std::cout << "result=" << accumulate_future.get() << '
    ';
        work_thread.join();  // wait for thread completion
     
        // Demonstrate using promise<void> to signal state between threads.
        std::promise<void> barrier;
        std::future<void> barrier_future = barrier.get_future();
        std::thread new_work_thread(do_work, std::move(barrier));
        barrier_future.wait();
        new_work_thread.join();
    }
    
  • 相关阅读:
    Switch
    java 函数 运算符
    java 基本类型
    更新时电话查重
    微信公众平台发送模板消息时连发三遍的最简单解决办法
    Yii2.0 发送邮件时中文附件乱码的问题
    Yii2.0 发送文件
    Yii2.0 请求
    Yii2.0随笔 路由
    yii2.0 在save保存之前的操作(放在模型model文件内)
  • 原文地址:https://www.cnblogs.com/mangoczp/p/13646800.html
Copyright © 2011-2022 走看看