• 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();
    }
    
  • 相关阅读:
    随性
    PHP csv文件处理时中文转码
    content...
    macro
    docker Alpine 编译安装node.js的dockerfile文件
    docker hub登录不上一直卡的原因
    java接口与模式(观察者)
    java模式的一点感受
    编码原则之接口隔离
    如何获取web应用的部署路径(多种方式)
  • 原文地址:https://www.cnblogs.com/mangoczp/p/13646800.html
Copyright © 2020-2023  润新知