类中的 pthread 函数 [英] pthread function from a class

查看:42
本文介绍了类中的 pthread 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类,例如

class c { 
    // ...
    void *print(void *){ cout << "Hello"; }
}

然后我有一个 c 的向量

And then I have a vector of c

vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());

现在,我想在 c.print();

下面给了我下面的问题:pthread_create(&t1, NULL, &c[0].print, NULL);

And the following is giving me the problem below: pthread_create(&t1, NULL, &c[0].print, NULL);

错误输出:无法将‘void* (tree_item::)(void)’转换为‘void*()(void)’ 用于参数 ‘3’ 到 ‘int pthread_create(pthread_t*, constpthread_attr_t*, void* ()(void), void*)’

Error Ouput: cannot convert ‘void* (tree_item::)(void)’ to ‘void* ()(void)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)’

推荐答案

你不能按照你写的方式来做,因为 C++ 类成员函数有一个隐藏的 this 参数传入.pthread_create() 不知道要使用什么 this 的值,所以如果你试图通过将方法转换为适当类型的函数指针来绕过编译器,你会出现分段错误.您必须使用静态类方法(没有 this 参数)或普通函数来引导类:

You can't do it the way you've written it because C++ class member functions have a hidden this parameter passed in. pthread_create() has no idea what value of this to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this parameter), or a plain ordinary function to bootstrap the class:

class C
{
public:
    void *hello(void)
    {
        std::cout << "Hello, world!" << std::endl;
        return 0;
    }

    static void *hello_helper(void *context)
    {
        return ((C *)context)->hello();
    }
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);

这篇关于类中的 pthread 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆