0

I read many answers on stackoverflow, but I didn't get any appropriate answer to why a static member needs to be created to serve as the thread-start function passed to pthread_create.

Now we come to my problem: As usual, I create a pthread, and call pthread_create() from a member function of the structure. I pass another member function as the thread-start function:

struct RecoveryServerConnector
{
  void Init(string ip, uint16_t port)
    {      
      pthread_t pth;
      pthread_create(&pth,NULL,&RunThread_Poller,this);
    }
    void *ConnectionPoller(void*)
    {
     //some work here
    }
};

But the compiler rejects my code with the following error:

error: cannot convert 'void* (RecoveryServerConnector::*)(void*)' to 'void* (*)(void*)' for argument '3' to 'int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)'

I can solve that problem by making the thread-start function static:

struct RecoveryServerConnector
 {
    void Init(string ip, uint16_t port)
    {      
     pthread_t pth;
     pthread_create(&pth,NULL,&RunThread,this);
    }
    void ConnectionPoller()
    {
      //some work here
    }
     static void* RunThread(void* context)
    {
      (RecoveryServerConnector*)(context)->ConnectionPoller();
    }

};

Why is it necessary to use the latter form?

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • I want to know the reason why static we need to create here? – Pankaj Belwal Dec 28 '19 at 02:42
  • The first answer in the linked question answers that: "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)" – sonicwave Dec 28 '19 at 09:30

0 Answers0