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

后端 未结 3 1680
失恋的感觉
失恋的感觉 2021-01-06 01:34

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

cannot convert \'*void(CameraManager:: * )(void*) to

相关标签:
3条回答
  • 2021-01-06 02:20

    If you want the function to be a member of the class, it must be static. It's because the thread function will be called directly and will not have a valid this pointer. This can be solved by having a wrapper function, that gets passed the actual object and then calls the proper member function:

    void *dequeueLoopWrapper(void *p)
    {
        CameraManager *cameraManager = static_cast<CameraManager*>(p);
        camereraManager->dequeueLoop();
        return nullptr;
    }
    
    // ...
    
    void CameraManager::startDequeuing()
    {
        dequeuing = true;
        dequeueThreadId = pthread_create(&dequeueThread, NULL, dequeueLoopWrapper, this);
    }
    

    However, I would recommend you start using the threading support in the new standard library:

    void CameraManager::startDequeuing()
    {
        dequeuing = true;
        myThread = std::thread(&CameraManager::dequeueLoop, this);
    }
    
    0 讨论(0)
  • 2021-01-06 02:21

    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);
    
    0 讨论(0)
  • 2021-01-06 02:38

    You can't use a pointer to member function as a function pointer unless it's static. You'll have to make dequeueLoop a free function, or write a free function as a wrapper to it.

    To access the class members in a free function, you should have the function pass it's this pointer as the final argument of pthread_create. Then have the free function cast it's argument to a pointer to the class.

    0 讨论(0)
提交回复
热议问题