0

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*)

Community
  • 1
  • 1
stan
  • 4,885
  • 5
  • 49
  • 72

4 Answers4

2

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.

Dr1Ku
  • 2,875
  • 3
  • 47
  • 56
Todd Gardner
  • 13,313
  • 39
  • 51
0

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.

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78
0

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);
ChauhanTs
  • 439
  • 3
  • 6
-1

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
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489