pthread function from a class

前端 未结 9 1212
天命终不由人
天命终不由人 2020-11-22 01:00

Let\'s say I have a class such as

class c { 
    // ...
    void *print(void *){ cout << \"Hello\"; }
}

And then I have a vector of c

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 01:37

    You'll have to give pthread_create a function that matches the signature it's looking for. What you're passing won't work.

    You can implement whatever static function you like to do this, and it can reference an instance of c and execute what you want in the thread. pthread_create is designed to take not only a function pointer, but a pointer to "context". In this case you just pass it a pointer to an instance of c.

    For instance:

    static void* execute_print(void* ctx) {
        c* cptr = (c*)ctx;
        cptr->print();
        return NULL;
    }
    
    
    void func() {
    
        ...
    
        pthread_create(&t1, NULL, execute_print, &c[0]);
    
        ...
    }
    

提交回复
热议问题