zoukankan      html  css  js  c++  java
  • 线程--promise furture 同步

    http://www.cnblogs.com/haippy/p/3279565.html

    std::promise 类介绍

    promise 对象可以保存某一类型 T 的值,该值可被 future 对象读取(可能在另外一个线程中),因此 promise 也提供了一种线程同步的手段。在 promise 对象构造时可以和一个共享状态(通常是std::future)相关联,并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。

    可以通过 get_future 来获取与该 promise 对象相关联的 future 对象,调用该函数之后,两个对象共享相同的共享状态(shared state)

    • promise 对象是异步 Provider,它可以在某一时刻设置共享状态的值。
    • future 对象可以异步返回共享状态的值,或者在必要的情况下阻塞调用者并等待共享状态标志变为 ready,然后才能获取共享状态的值。
    #include <iostream>       // std::cout
    #include <functional>     // std::ref
    #include <thread>         // std::thread
    #include <future>         // std::promise, std::future
    
    void print_int(std::future<int>& fut) {
        int x = fut.get(); // 获取共享状态的值.
        std::cout << "value: " << x << '
    '; // 打印 value: 10.
    }
    
    int main ()
    {
        std::promise<int> prom; // 生成一个 std::promise<int> 对象.
        std::future<int> fut = prom.get_future(); // 和 future 关联.
        std::thread t(print_int, std::ref(fut)); // 将 future 交给另外一个线程t.
        prom.set_value(10); // 设置共享状态的值, 此处和线程t保持同步.
        t.join();
        return 0;
    }
    #include <iostream>       // std::cin, std::cout, std::ios
    #include <functional>     // std::ref
    #include <thread>         // std::thread
    #include <future>         // std::promise, std::future
    #include <exception>      // std::exception, std::current_exception
    
    void get_int(std::promise<int>& prom) {
        int x;
        std::cout << "Please, enter an integer value: ";
        std::cin.exceptions(std::ios::failbit);   // throw on failbit
        try {
            std::cin >> x;                         // sets failbit if input is not int
            prom.set_value(x);
        }
        catch (std::exception&) {
            prom.set_exception(std::current_exception());
        }
    }
    
    void print_int(std::future<int>& fut) {
        try {
            int x = fut.get();
            std::cout << "value: " << x << '
    ';
        }
        catch (std::exception& e) {
            std::cout << "[exception caught: " << e.what() << "]
    ";
        }
    }
    
    int main()
    {
        std::promise<int> prom;
        std::future<int> fut = prom.get_future();
    
        std::thread th1(get_int, std::ref(prom));
        std::thread th2(print_int, std::ref(fut));
    
        th1.join();
        th2.join();
        return 0;
    }
  • 相关阅读:
    关于hive Metadata 使用 MsSQL
    hdp 2.06 安装备忘
    对于自我管理 ObjectContextManager的测试
    关于 Linq to EF 的内存泄漏问题
    使用过多的递归出现错误,“System.StackOverflowException”类型的未经处理的异常在 mscorlib.dll 中发生
    PowerShell 如何 远程连接【转】
    win7系统浏览器老是自动弹出网页怎么办
    win10如何深度清理C盘
    Win7电脑系统崩溃怎么解决?
    win7磁盘打不开如何解决
  • 原文地址:https://www.cnblogs.com/yuguangyuan/p/5858806.html
Copyright © 2011-2022 走看看