首页 >后端开发 >C++ >如何将 C 类成员函数传递给 pthread_create()?

如何将 C 类成员函数传递给 pthread_create()?

Barbara Streisand
Barbara Streisand原创
2024-12-26 01:17:10553浏览

How Can I Pass a C   Class Member Function to pthread_create()?

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn