pthread function from a class

前端 未结 9 1222
天命终不由人
天命终不由人 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条回答
  •  Happy的楠姐
    2020-11-22 01:27

    You can't do it the way you've written it because C++ class member functions have a hidden this parameter passed in. pthread_create() has no idea what value of this to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this parameter), or a plain ordinary function to bootstrap the class:

    class C
    {
    public:
        void *hello(void)
        {
            std::cout << "Hello, world!" << std::endl;
            return 0;
        }
    
        static void *hello_helper(void *context)
        {
            return ((C *)context)->hello();
        }
    };
    ...
    C c;
    pthread_t t;
    pthread_create(&t, NULL, &C::hello_helper, &c);
    

提交回复
热议问题