Cannot convert from type void * (classname: :) ​​() to input void * (*) (void *)

class Scoreget{ private: //some variables public: Scoreget(){ //something here } void* basicgetscore(){ //somthing here } void getscore(Scoreget s){ pthread_t t; if(pthread_create(&t,NULL,s.basicgetscore,NULL)==-1){ printf("Error 3\n"); exit(3); } void *a; if(pthread_join(t,&a)==-1){ printf("Error \n); exit(4); } } }; 

I am trying to start a separate thread to call a function because it uses the execl () call and thus stops my program (I am in windows and cannot use fork ()). Combining threads with classes gives me tough times.

From some googling, I realized that I need to make this last friend a function or static and use some kind of this pointer. I tried on my part, but the pieces do not fit together. I can’t even change the type of error. Now it upsets me. Getting the same error:

cannot convert Scoreget :: basicgetscore from type void * (Scoreget ::) () to input void * (*) (void *)

+8
c ++ multithreading
source share
3 answers

Declare it static and add another helper method:

 static void* basicgetscore(void * object){ return ((Scoreget *) object)->dobasicgetscore(); } void * dobasicgetscore() // new helper method { // do stuff here return NULL; } 

create pthread with:

 if (pthread_create(&t,NULL,basicgetscore,&s) == -1) { ... 

Also, be very careful. You pass this thread the address of a temporary variable. This is safe in this particular case, because pthread_join is in the same function, but if you must return from the function before the thread exits, you will free the object in which you are using the thread inside, which can lead to all kinds of unpleasant behavior. Try updating your function to either 1) take a link or pointer, or 2) work with this .

+8
source share

You cannot pass a non-static method to pthread_create

The easiest way: create a static method that will run basicgetscore

Something like that

 static void *Scoreget::basicgetscore_starter(void *p) { Scoreget *t = (Scoreget *)p; t->basicgetscore(); } pthread_create(&t,NULL,&Scoreget::basicgetscore_starter,(void *)&s); 
+6
source share

You need to define a non member (static) function to pass as the thread function for pthread_create() . A reference to your object does not help, as it is a pointer to a function expected from this function. You can pass a pointer to an instance of an object using the user pointer args void *.

0
source share

All Articles