Passing Class Functions to pthread_create()
Let's consider a scenario where we have a C class containing a member function, "print," which we want to execute in a separate thread using pthread_create().然而,我们遇到了一个编译错误:
pthread_create(&t1, NULL, &c[0].print, NULL);
的原因
此错误是由于 C 类成员函数隐式包含一个指向当前类的 this 指针作为其第一个参数。然而,pthread_create() 期望一个标准函数指针,它没有 this 指针。因此,编译器无法将此类函数指针转换为 pthread_create() 所需的函数类型。
解决方案
为了解决这个问题,我们需要采用一种替代方法,允许我们从pthread_create() 中调用类成员函数。有两种常见的方法:
使用静态类方法
静态类方法不包含 this 指针,因为它没有关联特定的类实例。它可以像普通函数一样调用,如下所示:
class C { public: static void *hello(void) { std::cout << "Hello, world!" << std::endl; return 0; } }; int main() { pthread_t t; pthread_create(&t, NULL, &C::hello, NULL); ... }
使用包装函数
另一种方法是创建将类成员函数包装为普通函数的包装函数。这个包装函数接受类实例作为其第一个参数,并调用成员函数,如下所示:
class C { public: void *hello(void) { std::cout << "Hello, world!" << std::endl; return 0; } static void *hello_helper(void *context) { return ((C *)context)->hello(); } }; int main() { C c; pthread_t t; pthread_create(&t, NULL, &C::hello_helper, &c); ... }
以上是如何将 C 类成员函数传递给 pthread_create()?的详细内容。更多信息请关注PHP中文网其他相关文章!