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;
    }
  • 相关阅读:
    NET控件关于Popup Win控件的使用介绍(消息提示控件)[转]
    .net从数据库二进制字段下载附件(文件),解决中文乱码
    测试页面的运行时间
    HashTable 遍历的两种方法
    100款国外xhtml+css模板(免费)
    在SharpDevolop中使用wix3制作中文安装包
    ASP.NET中的Session解析(一)
    兴奋,我的小站GBA365成长中
    泛型集合的序列化和反序列化
    asp.net mvc项目只能运行在iis根目录下吗?
  • 原文地址:https://www.cnblogs.com/yuguangyuan/p/5858806.html
Copyright © 2011-2022 走看看