多线程编程C+----第4课(子线程参数传递)

之前写的子线程,子线程的初始状态都是空的,即没有任何参数传入;现在测试子线程参数传递的情况,分别传入:int,float,string 和类。
学习使用std::ref(传入参数),该函数是引用传递,目的是让子程序对传入参数有访问权限,即修改和读取权限。输出结果如图
指针传递的话如下
int* a =10;
void thread_f(int* arg){
cout<<*arg<<endl;
}
thread th(thread_f,&a);

// pthread.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <thread>
#include <windows.h>
#include <string>
using namespace std;

bool is_exit = 0 ;

class person {
public:
    person() {
        cout << "person was constructed"<< endl;
    }
    ~person() {
        cout << "person was died" << endl;
    }
    void set_message(string name, string gender, unsigned int age) {
        this->name = name;
        this->gender = gender;
        this->age = age;
    }

    void show_Message() {
        cout << this->name <<" "<< this->gender << " " << this->age << endl;
    }

private:
    string name;
    string gender;
    unsigned int age;
};
void ThreadMain1(int a, float b, string c) { //子线程1
    cout << "1:thread 's id :" <<this_thread::get_id()<< endl;
    cout << a << " " << b << " " << c << endl;
}
void ThreadMain2(person &p) { //子线程2
    cout << "2:thread was begin!!,son's id :" << this_thread::get_id() << endl;
    p.show_Message();
}
int main()
{       
         cout << " I am father,my ID:" <<this_thread::get_id()<<endl; 
         int a = 110;
         float b = 120.0;
         string c = "消防电话:119";
         
         //实例化一个对象
         person p;
         p.set_message("hcp", "男", 26);

         //子线程id &&//子线程创建
        thread th1(ThreadMain1,a,b,c);  //  子线程在c11(thread) 作为一个对象,初始化,示例名称为th ,类名称 thread
        thread th2(ThreadMain2,std::ref(p)); // 参数传递:int float string class

        Sleep(3000);
        //is_exit = 1;//th1,th2 会知道自己必须退出当前做的事情,直接返回,然后使用join回收线程
        th1.join(); 
        th2.join();

        return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值