zoukankan      html  css  js  c++  java
  • c/c++ 多线程 多个线程等待同一个线程的一次性事件

    多线程 多个线程等待一个线程的一次性事件

    背景:从多个线程访问同一个std::future,也就是多个线程都在等待同一个线程的结果,这时怎么处理。

    办法:由于std::future只能被调用一次get方法,也就是只能被某一个线程等待(同步)一次,不支持被多个线程等待。所以std::sharted_future,就应运而生了。

    特点:std::sharted_future可以被复制,std::future是不可以的被复制的。

    std::sharted_future的3种创建方式(fut为std::future):

    1,std::shared_future<int> sf2(std::move(fut));

    2,std::shared_future<int> sf2 = fut.share();

    3,std::shared_future<int> sf1(pro.get_future());

    代码:

    #include <iostream> 
    #include <future>     
    
    int do_get_value() { return 10; }
    void th1(std::shared_future<int> sf){
      std::cout << sf.get() << std::endl;
    }
    void th2(std::shared_future<int> sf){
      std::cout << sf.get() << std::endl;
    }
    int main(){
      std::future<int> fut = std::async(do_get_value);
      //std::shared_future<int> sf2(std::move(fut));
      //std::shared_future<int> sf2 = fut.share();
      //std::thread t1(th1, sf2);
      //std::thread t2(th1, sf2);
    
      //t1.join();
      //t2.join();
      std::promise<int> pro;
      std::shared_future<int> sf1(pro.get_future());
      std::thread t1(th1, sf1);
      std::thread t2(th1, sf1);
      pro.set_value(110);
      t1.join();
      t2.join();
    }
    

    github源代码

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

    本人微信:xiaoshitou5854

  • 相关阅读:
    【Solr】copy字段的应用
    【Solr】Solr的安装部署
    【UEditor】 UEditor整合项目上传资源到阿里云服务器
    【Bootstrap】Bootstrap和Java分页-第二篇
    【Bootstrap】Bootstrap和Java分页-第一篇
    工作那点小事
    ubuntu安装mongodb
    mybatis插入返回主键
    linux查看端口占用命令
    ubuntu安装ssh
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/10029493.html
Copyright © 2011-2022 走看看