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();
    }
    
  • 相关阅读:
    Electron中git, npm,webpack使用
    Luogu_2061_[USACO07OPEN]城市的地平线City Horizon
    Luogu_1080_国王游戏
    Luogu_2878_[USACO07JAN]保护花朵Protecting the Flowers
    GYOJ_1812_股票(stock)
    JXJJOI2018_三题
    JXJJOI2018_T3_catch
    JXJJOI2018_T1_market
    JXJJOI2018_T2_tank
    Luogu_2876_[USACO07JAN]解决问题Problem Solving
  • 原文地址:https://www.cnblogs.com/mangoczp/p/13646800.html
Copyright © 2011-2022 走看看