boost-users-bounces@lists.boost.org <> wrote:
I haven't been able to find any clear explanation about this, so here it goes:
I'm coding a multithreaded program using pthreads. The general behaviour is this:
-A function starts. -The function creates a shared pointer "OBJ". -The function creates a Thread, passing "OBJ" as the parameter (having to cast it as void*). -The thread starts, getting a (void*) param which is casted back to "OBJ" (shared pointer type). -The function ends, and therefore its "OBJ" goes out of scope. -The thread" ends, so its "OBJ" goes out of scope too. (of course, the thread could at times end before the function instead)
I'm afraid that the shared pointer does not behave well due to those nasty void* casts... maybe trying to delete twice the object. What's the proper way of coding this? Weak pointers maybe?
Thanks a lot for any help.
The first problem I see is that a boost::shared_ptr is not the same size
as a void*. The believe the cast would slice off the pointer to the
reference count. I would try something like the following (untested):
//Notice that we are passing the shared pointer by value. I
//consider this important because we are about to abuse it.
void Spawn_thread (boost::shared_ptr <whatever> value)
{
pthread_t thread;
pthread_attr_t attr;
//Notice that I'm passing a raw pointer to the shared pointer.
if (!pthread_create (&thread, &attr, &Thread_main, &value))
{
//Wait for the new thread to copy its parameter into a
//local variable
Wait_for_signal();
}
else
{
//Error handling
}
}
void *Thread_main (void *arg)
{
//Dereference the argument (to get back the shared pointer),
copy
//it into a local shared pointer and allow the main thread to
proceed
boost::shared_ptr <whatever> parameter = *reinterpret_cast