类中的 pthread 函数

pthread function from a class(类中的 pthread 函数)
本文介绍了类中的 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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)