This is somewhat similiar to this : pthread function from a class
But the function that's getting called in the end is referencing the this pointer, so it cannot be made static.
void * Server::processRequest()
{
std::string tmp_request, outRequest;
tmp_request = this->readData();
outRequest = this->parse(tmp_request);
this->writeReply(outRequest);
}
void * LaunchMemberFunction(void * obj)
{
return ((Server *)obj)->processRequest();
}
and then the pthread_create
Server SServer(soc);
pthread_create(&handler[tcount], &attr, (void*)LaunchMemberFunction,(void*)&SServer);
errors:
SS_Twitter.cpp:819: error: invalid conversion from void* to void* ( )(void ) SS_Twitter.cpp:819: error: initializing argument 3 of int pthread_create(pthread_t*, const pthread_attr_t*, void* ( )(void ), void*)
You are casting the third argument to a void* ((void*)
, and then getting an error, as void*
cannot be cast to a function pointer.
I believe it should compile if you just use &LaunchMemberFunction
instead.
get rid of the (void*) in front of LaunchMemberFunction. It's both unecessary and incorrect, and the cause of your error. The language will not implicitly convert from void * to a pointer to function type, which would be needed for the code you have written to work. That argument to pthread_create is already the right type, there is no reason to cast it to something else.
In your definition of function I don't see input argument type please use as the following
void * Server::processRequest(void)
{
std::string tmp_request, outRequest;
tmp_request = this->readData();
outRequest = this->parse(tmp_request);
this->writeReply(outRequest);
}
Second thing you do not have to case a function pointer just use as the following
pthread_create(&handler[tcount], &attr, &LaunchMemberFunction,(void*)&SServer);
The problem is with the cast. You are casting the function pointer to a void*
that can not be implicitly converted to ( void (*)(void*)
--which is the type accepted by pthread_create
for the third argument.
You do not need to cast the argument as it is of the exact type, but if you had to, it would be:
void LaunchMemberFunction( Server * ); // signature now does not match, cast required:
static_cast<void (*)(void*)>(LaunchMemberFunction)
// or with C casts:
(void (*)(void*))LaunchMemberFunction
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.