On Tue, Dec 18, 2007 at 10:28:37AM -0500, Andrew Holden wrote:
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):
He might just allocate the shared_ptr on the heap (the dynamic memory allocation
will be anyway cheaper than thread creation):
void *thread(void *ptr)
{
shared_ptr<X> *_p = static_cast