1.入口函数为类的公有成员函数
#include <iostream>
#include <thread>
class MyClass
{
public:
void func()
{
std::cout << "Thread " << std::this_thread::get_id()
<< " started" << std::endl;
// do some work
std::cout << "Thread " << std::this_thread::get_id()
<< " finished" << std::endl;
}
};
int main()
{
MyClass obj;
std::thread t(&MyClass::func, &obj);//调用方式为:域名::函数名,类对象引用或指针
// std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();
//std::thread t(&MyClass::func, obj);
t.join();
return 0;
}
2.入口函数为类的私有成员函数
#include <iostream>
#include <thread>
class MyClass
{
private:
friend void myThreadFunc(MyClass* obj);
void privateFunc()
{
std::cout << "Thread "
<< std::this_thread::get_id() << " privateFunc" << std::endl;
}
};
void myThreadFunc(MyClass* obj)
{
obj->privateFunc();
}
int main()
{
MyClass obj;
std::thread thread_1(myThreadFunc, &obj);
thread_1.join();
return 0;
}
上面的代码中,将 myThreadFunc 定义为 MyClass 类的 *友元函数,并在函数中调用 privateFunc 函数。在创建线程时,需要将类对象的指针作为参数传递给线程。