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();
    }
    
  • 相关阅读:
    GPU上的基本线性代数
    NVIDIA数据中心深度学习产品性能
    GeforceRTX系列参数对比
    NVIDIA CUDA-X AI
    NVIDIA 认证系统
    汉字手写训练和识别
    动态表单工作量给后端
    机器学习PAL数据可视化
    越是向前 越受阻力
    Caused by: java.lang.IllegalStateException: java.lang.IllegalStateException: Cannot emit more than one data
  • 原文地址:https://www.cnblogs.com/mangoczp/p/13646800.html
Copyright © 2011-2022 走看看