zoukankan      html  css  js  c++  java
  • C++基础-多线程通信(promise)

    使用promise创造一个全局的类型数据, 接收方和发送方, 通过这个数据进行进场的通信 

    接收方, 创建接收的结构体

    future<int> fu = vall.get_future()

    发送方, 设置value

    vall.set_value(5201314);

    接收方, 使用.get获取数据

    cout << fu.get() << endl;

    全部代码

    //
    // Created by Administrator on 2021/6/27.
    //
    #include<future>
    #include<iostream>
    #include<string>
    #include <cstdlib>
    
    using namespace std;
    
    int main1()
    {
        string str1("12345");
        string str2("12345");
        string str3(str1 + str2); //C++风格字符串
        cout << str3 << endl;
        cin.get();
    }
    
    promise<string>val; //全局通信变量
    
    int main2()
    {
        thread th1([]()
        {
            future<string> fu = val.get_future(); //获取未来状态
            cout << "wait" << endl;
            cout << fu.get() << endl;
        });
    
        thread th2([](){
            system("pause");
            val.set_value("fangfang with huahua");
            system("pause");
        });
    
        th1.join();
        th2.join();
    //    cin.get();
        return 0;
    }
    
    promise<int>vall; //全局通信变量
    int main()
    {
        thread th1([]()
                   {
                       future<int> fu = vall.get_future(); //获取未来状态
                       cout << "wait" << endl;
                       cout << fu.get() << endl;
                   });
    
        thread th2([](){
            system("pause");
            vall.set_value(5201314);
            system("pause");
        });
    
        th1.join();
        th2.join();
    //    cin.get();
        return 0;
    }
  • 相关阅读:
    构造方法,析构函数
    Redis Sentinel实现的机制与原理详解
    关于PageRank的总结
    再次建立wordpress
    图的研究杂记
    并行的论文
    还是bib问题
    如何解决bib的一些问题
    忙中记录
    近期一些学术相关记录
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/14940496.html
Copyright © 2011-2022 走看看