Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert from type void*(classname::) () to type 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 run a separate thread for calling a function,because it uses a call to execl(), and thus will stop my program (I am on windows and cannot use fork()). Combining threading with classes is giving me hard times.

From some googling I understood I need to make that last function friend or static and use some sort of this pointer. I have tried on my part but pieces are not fitting together. I am even unable to change the error type. Its frustrating me now. Getting same error:

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

like image 543
vish213 Avatar asked Aug 20 '12 18:08

vish213


2 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're giving this thread the address of a temporary variable. It's safe in this specific case because the pthread_join is in the same function, but if you were to return from the function before the thread exits, you'll deallocate the object you're running the thread inside, which could result in all kinds of nasty behavior. Consider updating your function to either 1) take a reference or pointer or 2) operate on this.

like image 99
Wug Avatar answered Sep 20 '22 15:09

Wug


You can't pass non static method to pthread_create

The most simple way, create static method which would run basicgetscore

Something like this

static void *Scoreget::basicgetscore_starter(void *p) {
    Scoreget *t = (Scoreget *)p;
    t->basicgetscore();
}

pthread_create(&t,NULL,&Scoreget::basicgetscore_starter,(void *)&s);
like image 31
CyberDem0n Avatar answered Sep 18 '22 15:09

CyberDem0n