- 线程ID:std::this_thread::get_id()获取线程ID
- 传递类对象时:虽然线程入口采用引用接收,但并不是真实的引用,而是相当于值传递,要调用一次拷贝构造;只有在传参时加上std::ref()才是真实的引用
- 当传入智能指针时,需要使用std::move()转换
- 用类的成员函数作为线程参数 (参数分别为 &成员函数名,对象名,参数)
#include <iostream>
#include <thread>
using namespace std;
class A
{
public:
int m_i;
A(int a):m_i(a){
cout<<"构造函数执行,地址为:"<<this<<" thread_ID: "<<std::this_thread::get_id()<<endl;
}
A(const A &a):m_i(a.m_i){
cout<<"拷贝构造函数执行,地址为:"<<this<<" thread_ID: "<<std::this_thread::get_id()<<endl;
}
void thread_word(int num)
{
cout<<"子线程3开始"<<endl;
cout<<"子线程3参数地址是:"<<this<<" thread_ID: "<<std::this_thread::get_id()<<endl;
cout<<"子线程3结束"<<endl;
}
~A(){
cout<<"析构函数执行,地址为:"<<this<<" thread_ID: "<<std::this_thread::get_id()<<endl;
}
};
void myprint(const A &buff)
{
cout<<"子线程开始"<<endl;
cout<<"子线程参数地址是:"<<&buff<<" thread_ID: "<<std::this_thread::get_id()<<endl;
cout <<"buff.m_i="<< buff.m_i<<endl;
cout<<"子线程结束"<<endl;
}
void myprint2(unique_ptr<int> buff)
{
cout<<"子线程2开始"<<endl;
cout<<"子线程2参数地址是:"<<&buff<<" thread_ID: "<<std::this_thread::get_id()<<endl;
cout<<"子线程2结束"<<endl;
}
int main()
{
cout <<"主线程开始"<<" thread_ID: "<<std::this_thread::get_id()<<endl;
int num=2;
A myobj(num);
thread thread1(myprint,std::ref(myobj));
thread1.join();
unique_ptr<int> myptr(new int(100));
thread thread2(myprint2,std::move(myptr));
thread2.join();
thread thread3(&A::thread_word,myobj,15);
thread3.join();
cout<<"主线程结束"<<endl;
return 0;
}