检查连接流程中,需要不断发送和接收socket消息,由于socket在发送和接收udp的过程是阻塞的,所以打算分别启动两个线程用来发送和接收socket的消息。
这里记录一下启动线程调用类中的成员函数的方式
如果在类里面启动线程调用成员函数,则直接将成员函数的地址和this指针传入线程,其他参数传入方式不变
class MyClass
{
public:
int a;
void th1() {
std::cout << "print hello" << std::endl;
std::cout << "a: " << a << std::endl;
};
void th2(int &i, int j) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::cout << a * i * j << std::endl;
}
void start(int &i, int j) {
int n = 3;
std::thread t1(&MyClass::th1, this);
std::thread t2(&MyClass::th2, this, std::ref(i), j);
t1.detach();
t2.detach();
};
};
int main() {
MyClass my;
my.a = 5;
int k = 2;
int p = 3;
my.start(k, p);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return 0;
}
如果在类外调用类的成员函数,需要将成员函数的地址和类的具体对象传入线程
class MyClass
{
public:
int a;
void th1() {
std::cout << "print hello" << std::endl;
std::cout << "a: " << a << std::endl;
};
void th2(int &i, int j) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::cout << a * i * j << std::endl;
}
};
int main() {
MyClass my;
my.a = 5;
int k = 2;
int p = 3;
std::thread t1(&MyClass::th1, &my);
std::thread t2(&MyClass::th2, &my, std::ref(k), p);
t1.detach();
t2.detach();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return 0;
}
在网上还看到有说把成员函数设置成static,但是缺点是没法使用this指针。还有设置成友元函数的方式。