cannot convert from type void*(classname::) () to type void*(*)(void*)

前端 未结 3 1041
情深已故
情深已故 2021-02-15 15:16
class Scoreget{
    private:
        //some variables
    public:
        Scoreget(){
            //something here
        }

        void* basicgetscore(){
                     


        
相关标签:
3条回答
  • 2021-02-15 15:27

    You need to define a non member (static) function to pass as thread function for pthread_create(). Referencing from your object doesn't help, since this is a function pointer that is expected from this function. You can pass a pointer to your object instance using the user args void* pointer though.

    0 讨论(0)
  • 2021-02-15 15:38

    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);
    
    0 讨论(0)
  • 2021-02-15 15:47

    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.

    0 讨论(0)
提交回复
热议问题