类内使用 pthread_create 时,第三个参数为什么必须是静态函数

博客探讨了在C++中使用pthread_create创建线程时,为何需要将成员函数指定为静态的原因。由于成员函数隐含了一个this指针,不兼容线程函数所需的void指针参数。解决方法是使用静态成员函数,但这样无法直接调用非静态成员。文中提到了两种解决方案:通过类的静态对象或传递类实例给静态函数。线程池中采用后者,如示例所示,将this指针传递给静态worker函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <pthread.h>
int pthread_create(pthread_t* thread, const pthread_attr_t* attr,
					void *(*start_routine)(void*), void *arg);

以上是 pthread_create() 的声明。
但是在学习《Linux高性能服务器编程》,实现线程池的时候,发现有这么一句话

类内使用 pthread_create 函数时,将函数的第 3 个参数指向一个静态函数(必须是静态函数)。

百思不得其解,遂查了一部分资料得到以下解答:

在类内调用 pthread_create ,并且想要将成员函数作为参数的时候,实际传参过程中,还会传递 this 指针(就这儿)

If you are rusty on your C++, let me remind you of the problem. Every C++ member function has a hidden first passed parameter known as the this parameter. Via the this parameter, the function knows which instance of the class to operate upon. Because you never see these this parameters, it is easy to forget they exist.
Now, let’s again consider the _beginthread() function which allows us to specify an arbitrary entry-point-function for our new thread. This entry-point-function must accept a single void* passed param. Aye, there’s the rub. The function signature required by _beginthread() does not allow the hidden this parameter, and hence a C++ member function cannot be directly activated by _beginthread().

C++类中的成员函数其实默认在参数中包含有一个this指针,这样成员函数才知道应该对哪个实例作用。而线程函数必须接受一个void指针作为参数,所以导致了矛盾。为了解决矛盾,我们可以使用static函数,它独立于实例,参数中将不会有this指针,所以可以用于打开线程。

所以我们需要传入的成员函数应该是 static 静态成员函数,但是怎么调用类内其他的方法呢?

有两种方法

《Linux高性能服务器编程》

  1. 通过类的静态对象来调用。比如单例模式中,静态函数可以通过类的全局唯一实例了来访问动态成员函数。
  2. 将类的对象作为参数传递给该静态函数,然后在静态函数中引用这个对象,并调用其动态方法。

线程池中使用的便是第二种方法

static void* worker( void* arg );
pthread_create( m_threads + i, NULL, worker, this )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Artintel

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值