之前写的子线程,子线程的初始状态都是空的,即没有任何参数传入;现在测试子线程参数传递的情况,分别传入: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;
}