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;
    }
  • 相关阅读:
    【HDOJ6666】Quailty and CCPC(模拟)
    【2019 Multi-University Training Contest 8】
    分布式锁的理解
    反射工具类【ReflectionUtils】
    Maven常用命令
    maven常用命令介绍
    mysql 优化策略(如何利用好索引)
    centos7搭建svn服务器及客户端设置
    Centos7 配置subversion
    Centos7更改网卡名称Eth0
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/14940496.html
Copyright © 2011-2022 走看看