casting to void* to pass objects to pthread in c++

前端 未结 2 527
我寻月下人不归
我寻月下人不归 2021-01-19 14:13

I\'m a little confused about how to pass an object to the pthread_create function. I\'ve found a lot of piecemeal information concerning casting to void*, passing arguments

2条回答
  •  一向
    一向 (楼主)
    2021-01-19 14:55

    If you want to go this route, I believe you want something like this:

    Edit: Based on James Kanze's answer, add a separate activate method to launch the thread after construction is finished.

    class GenericThread {
    protected:
        GenericThread () {
          //...
        }
        virtual ~GenericThread () {}
    
        int activate () {
            return pthread_create(..., GenericThreadEntry, this);
        }
    
        virtual void * thread_routine () = 0;
    
        #if 0
        // This code is wrong, because the C routine callback will do so using the
        // C ABI, but there is no guarantee that the C++ ABI for static class methods
        // is the same as the C ABI.
        static void * thread_entry (void *arg) {
            GenericThread *t = static_cast(arg);
            return t->thread_routine();
        }
        #endif
    };
    
    extern "C" void * GenericThreadEntry (void *) {
        GenericThread *t = static_cast(arg);
        return t->thread_routine();
    }
    

    Then, ProducerThread would derive from GenericThread.

    Edit: Searching for extern "C" in the C++ Standard. revealed no requirement that a function pointer must point to a function with C linkage to be callable by a C library routine. Since pointers are being passed, linkage requirements do not apply, as linkage is used to resolve names. A pointer to a static method is a function pointer, according to C++ 2011 draft (n3242), Sec. 3.9.2p3:

    Except for pointers to static members, text referring to pointers does not apply to pointers to members.

    Edit: Mea culpa. The C library will invoke the callback function assuming the C application binary interface. A function with C++ linkage may use a different ABI than the C ABI. This is why it is required to use a function with extern "C" linkage when passing to a callback function to a C library. My sincere apologies to James Kanze for doubting him, and my sincere thanks to Loki Astari for setting me straignt.

提交回复
热议问题