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?