zoukankan      html  css  js  c++  java
  • c/c++ 多线程 等待一次性事件 std::promise用法

    多线程 等待一次性事件 std::promise用法

    背景:不是很明白,不知道为了解决什么业务场景,感觉std::async可以优雅的搞定一切的一次等待性事件,为什么还有个std::promise。

    用法:和std::async一样,也能够返回std::future,通过调用get_future方法。也可以通过future得到线程的返回值。

    特点:

    1,是个模板类,模板类型是个方法类型,比如double(int),有一个参数,类型是int,返回值类型是double。

    std::promise<int> pro;//pro.get_future.get()的返回值为int类型
    

    2,在std::promise<T>的对象上,调用set_value后,future变成就绪(ready)状态,调用future对象的get方法的地方就由阻塞变为不阻塞了。

    std::promise<int> pro;
    pro.set_value(10);
    
    void thread1(std::promise<int>& p, int val){
      std::cout << "in thread1" << std::endl;
      p.set_value(val);
    }
    
    std::promise<int> pro;
    std::future<int> ft1 = pro.get_future();
    std::thread t1(thread1, std::ref(pro), 10);
    t1.detach();
    std::cout << ft1.get() << std::endl;
    

    3,std::promise的拷贝构造函数是被删除了的,所以std::promise作为函数的参数时,必须用std::ref(pro).

    代码:

    #include <future>
    #include <thread>
    #include <iostream>
    
    void thread1(std::promise<int>& p, int val){
      std::cout << "in thread1" << std::endl;
      p.set_value(val);
    }
    int main(){
      std::promise<int> p;
      std::future<int> f = p.get_future();
      std::thread t1(thread1, std::ref(p), 10);
      t1.detach();
    
      std::cout << f.get() << std::endl;
      pthread_exit(NULL);
    }
    

    github源代码

    c/c++ 学习互助QQ群:877684253

    本人微信:xiaoshitou5854

  • 相关阅读:
    react native mapbox MarkView只显示一个子组件问题
    react native mapbox 截图压缩(@react-native-mapbox-glmaps)
    @react-native-mapbox-gl/maps语言插件汉化不完善问题
    SQLSERVER优化
    springboot+react整合
    sqlserver求小数取位
    C#中Math.Round() 的真实含义
    Java Nio学习总结(一)
    Linq去重(自定义字段)
    WPF学习记录(一):布局
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/10016225.html
Copyright © 2011-2022 走看看