Search code examples
c++pthreadsfriendfriend-function

cannot convert '*void(MyClass::*)(void*) to void*(*)(void*) in pthread_create function


i'm trying to create a new thread with a class "CameraManager" but i have the following error:

cannot convert '*void(CameraManager:: * )(void*) to void*( * )(void*) in pthread_create function

i defined in the cameramanager.h file:

public:
void *dequeueLoop(void *ptr);

and in the cameramanager.cpp

void CameraManager::startDequeuing(){
dequeuing = true;
dequeueThreadId = pthread_create(&dequeueThread, NULL, &CameraManager::dequeueLoop, NULL);
}

void *CameraManager::dequeueLoop(void *ptr){
while(dequeuing){
    highSpeedCamera->dequeue();
    highSpeedCamera->enqueue();
}

I don't want to declare dequeueLoop as a static function i also tried to declare dequeueLoop as a class friend function in the following way but then it doesn't have scope on class variables 'highSpeedCamera' and 'dequeuing' and the compiler also tell me that 'dequeueLoop' was not declared in this scope

to make dequeueLoop a friend function i did:

cameramanager.h

public:
friend void *dequeueLoop(void *ptr);

cameramanager.cpp

void CameraManager::startDequeuing(){
    dequeuing = true;
    dequeueThreadId = pthread_create(&dequeueThread, NULL, &CameraManager::dequeueLoop, NULL);
}
void *dequeueLoop(void *ptr){
    while(dequeuing){
        highSpeedCamera->dequeue();
        highSpeedCamera->enqueue();
    }
}

Where i'm doing wrong?


Solution

  • I don't want to declare dequeueLoop as a static function

    If you want to use pthreads, then you'll need a static or non-member function for the entry point. You can pass a pointer to your object to this function, using it as a trampoline into the non-static member function:

    static void * dequeueEntry(void * self) {
        return static_cast<CameraManager*>(self)->dequeueLoop();
    }
    
    dequeueThreadId = pthread_create(
        &dequeueThread, NULL, 
        &CameraManager::dequeueEntry, // <-- pointer to trampoline function
        this);                        // <-- pointer to object for member function
    

    Alternatively, if you have a modern compiler, you could use the standard thread library instead:

    std::thread thread(&CameraManager::dequeLoop, this);