Boost logo

Boost Users :

From: Pete Chapman (p.chapman_at_[hidden])
Date: 2005-10-26 12:29:20


Phil Endecott wrote:
> That's fine, but it's not what I'm looking for right now. Can anyone
> point me to some code - perhaps adding a layer on top of boost::thread -
> that ties object lifetime to thread lifetime in some way? (I'm
> imagining a dynamically-allocated object the deletes itself when the
> thread's initial function terminates

That's possible - the thread could certainly delete its object at the
end of its lifetime. However if anyone else had a pointer to it, it
would be asking for access-of-deallocated-memory troubles. You could
avoid this via some some shared_ptr/weak_ptr mechanism, but then you've
moved away from the thread-lifetime == object-lifetime idea.

> and that kills the thread if it
> (the object) is deleted first.)

boost::thread doesn't give you a way to kill a thread, because it's
almost always a bad idea. What about desctructors for objects that were
on the thread's stack? Operations that it may have been halfway through
completing? (including memory allocation - you could be corrupting your
global heap)
I'm not saying it's always possible to have a thread exit nicely - but
in those circumstances, I begin thinking about moving that thread's work
into a seperate process (which you can usually kill without repercussions).

>
> The actual application is a sort of daemon; a main loop accepts tcp
> connections, and creates a new thread to handle each one. It normally
> wants to "fire and forget" these threads, and I imagine it creating them
> with new() and then letting them dangle, until they eventually terminate
> and delete themselves.

Why don't you create them and delete them immediately? The thread will
continue to run, even if the object is destroyed (as you've noticed ;-)


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