Aravind M
Aravind M

Reputation: 13

cannot convert from type void* (class name)(void*) to type void* (*)(void*) in a pthread

I am trying to create a thread in main function and call a function of another class through my thread.

In main.cpp:

SocketHandler *callserver;
pthread_t thread1;
pthread_create(&thread1,0, callserver->createSocket,NULL);

and in SocketHandler.h:

void* createSocket();

and in SocketHandler.cpp:

void * SocketHandler::createSocket()
{
    //....
}

When I am trying to compile main.cpp I am getting an error

 cannot convert SocketHandler::createSocket from type void* (SocketHandler::)() to type void* ( * )(void*)

Upvotes: 1

Views: 3448

Answers (1)

Sergio
Sergio

Reputation: 8209

pthread_create() accepts only pointers to regular functions or class functions, not to member functions. And that pointer must be void *(*)(void *). To workaround you can do next:

void *trampoline(void *arg) {
    SocketHandler *callServer = static_cast<SocketHandler *>(arg);
    callServer->createSocket();
    return nullptr;
}

// ...
SocketHandler *callserver;
pthread_t thread1;
pthread_create(&thread1,0, trampoline, callserver);

trampoline() may be inlined:

pthread_create(&thread1, 0, [](void* ptr){static_cast<SocketHandler*>(ptr)->createSocket(); return (void*)nullptr;}, callserver);

Alternatively you may use std::thread, that allows painless using of member functions too.

Upvotes: 3

Related Questions