线程指针和函数指针

Pthread and function pointers

本文关键字:指针 函数 线程      更新时间:2023-10-16

我对pthread的工作方式有点困惑-具体来说,我很确定pthread接受一个指向一个函数的指针,该函数以一个void指针作为参数(如果我错了请纠正我),并且我以这种方式声明了我的函数,但我仍然得到一个错误。这是我正在努力的代码:

void eva::OSDAccessibility::_resumeWrapper(void* x)
{
    logdbg("Starting Connection.");
    _listener->resume();
    logdbg("Connected.");
    pthread_exit(NULL);
}
void eva::OSDAccessibility::resumeConnection()
{    
    long t;
    _listener->setDelegate(_TD);
    pthread_t threads[1];
    pthread_create(&threads[0], NULL, &eva::OSDAccessibility::_resumeWrapper, (void *)t);
}

得到的错误是:

No matching function for call to pthread_create.

你不必告诉我如何修复代码(尽管这当然会很感激),我更感兴趣的是为什么这个错误会出现,如果我对pthread的理解是正确的。谢谢!:)

  1. 函数签名必须为void * function (void*)

  2. 如果从c++代码中调用,方法必须是静态的:

    class myClass
    {
        public:
        static void * function(void *);
    }
    

使用非静态方法的解决方案如下:

class myClass
{ 
    // the interesting function that is not an acceptable parameter of pthread_create
    void * function();
    public:
    // the thread entry point
    static void * functionEntryPoint(void *p)
    {
        ((myClass*)p)->function();
    }
}

启动线程:

myClass *p = ...;
pthread_create(&tid, NULL, myClass::functionEntryPoint, p);