|
Boost Users : |
From: Zeljko Vrba (zvrba_at_[hidden])
Date: 2007-12-18 10:58:07
On Tue, Dec 18, 2007 at 10:28:37AM -0500, Andrew Holden wrote:
> boost-users-bounces_at_[hidden] <> 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<shared_ptr<X>*>(ptr);
shared_ptr<X> p = *_p;
delete _p;
...
}
void creator()
{
...
pthread_create(&thrid, 0, thread, new shared_ptr<X>(orig_ptr));
...
}
No need for any additional synchronization.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net