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

前端 未结 2 524
我寻月下人不归
我寻月下人不归 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

    There are a number of problems with your code. For starters, I don't see where the arg you are casting is declared, so I can't say whether the case is appropriate.

    Perhaps more importantly, thread_routine is a member function, so it can't be converted to a pointer to a function. The function passed to pthread_create must be extern "C", so it cannot be a member, period; it must be a free function declare extern "C". If you want to call a member function, pass a pointer to the object as the last argument, and dereference it in the extern "C" function:

    extern "C" void* startProducerThread( void* arg )
    {
        return static_cast( arg )->thread_routine();
    }
    

    And to start the thread:

    int status = pthread_create( &thread, &thread_attr, startProducerThread, this );
    

    Just don't do this in a constructor. The other thread might start running before the object is fully constructed, with disasterous effects.

    Also, be very sure that the cast in startProducerThread is to exactly the same type as the pointer passed into pthread_create. If you cast to a base class in startProducerThread, then be very, very sure that it is a pointer to that base class that you pass to pthread_create; use an explicit cast if necessary (to the type in startProducerThread, not to void*).

    Finally, while not relevant to your actual question: if ProtectedBuffer has an interface like that of std::vector, and returns references to internal data, there's no way you can make it thread safe. The protection needs to be external to the class.

提交回复
热议问题