在类中起线程调用类里的成员函数

检查连接流程中,需要不断发送和接收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指针。还有设置成友元函数的方式。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值