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;
}
原文地址:https://www.cnblogs.com/my-love-is-python/p/14940496.html