1 传递临时对象作为线程参数
#include <iostream>
#include <thread>
#include <string>
using namespace std;
void myprint(const int i, const string &pmybuf)
{
cout << i << endl;
cout << pmybuf.c_str() << endl;
cout << "threadid is " << std::this_thread::get_id() << endl;
return;
}
int main()
{
int mvar = 1;
int &mvary = mvar;
char mybuf[] = "this is a test!";
thread mytobj(myprint, mvar, string(mybuf));
mytobj.join();
cout << "I QUIT! \n" << endl;
return 0;
}
2 传递类对象作为线程参数
#include <iostream>
#include <thread>
#include <string>
using namespace std;
class A
{
public:
int m_i;
A(int a) :m_i(a) { cout << "[A::A(int a)构造函数执行!] " << this << " threadid is " << std::this_thread::get_id() << endl; }
A(const A &a):m_i(a.m_i){ cout << "[A::A(const A)拷贝构造函数执行!] " << this << "threadid is " << std::this_thread::get_id() << endl; }
~A(){ cout << "[A::A()析构函数执行!] " << this << " threadid is " << std::this_thread::get_id() << endl; }
void thread_work(int num)
{
cout << "子线程 work 函数执行!] " << this << " threadid is " << std::this_thread::get_id() << endl;
}
void operator()(int num)
{
cout << "子线程 ()函数执行!] " << this << " threadid is " << std::this_thread::get_id() << endl;
}
};
void myprint2(A &pmybuf)
{
pmybuf.m_i = 199;
cout << "子线程pmybuf的参数地址是" << &pmybuf << "threadid is " << std::this_thread::get_id() << endl;
return;
}
int main()
{
A myobj(10);
thread mytobj2(myprint2, std::ref(myobj));
mytobj2.join();
cout << "主线程pmybuf的参数地址是" << &myobj << "threadid is " << std::this_thread::get_id() << endl;
cout << "I QUIT! \n" << endl;
return 0;
}
3 用成员函数指针做线程函数
#include <iostream>
#include <thread>
#include <string>
using namespace std;
class A
{
public:
int m_i;
A(int a) :m_i(a) { cout << "[A::A(int a)构造函数执行!] " << this << " threadid is " << std::this_thread::get_id() << endl; }
A(const A &a):m_i(a.m_i){ cout << "[A::A(const A)拷贝构造函数执行!] " << this << "threadid is " << std::this_thread::get_id() << endl; }
~A(){ cout << "[A::A()析构函数执行!] " << this << " threadid is " << std::this_thread::get_id() << endl; }
void thread_work(int num)
{
cout << "子线程 work 函数执行!] " << this << " threadid is " << std::this_thread::get_id() << endl;
}
};
int main()
{
A myobj4(10);
thread mytobj4(&A::thread_work, std::ref(myobj4), 15);
mytobj4.join();
cout << "I QUIT! \n" << endl;
return 0;
}