Re: Object model for self-terminating "threads"
Alan McKenney wrote:
I'm working on some code to handle interactions with a
server, and am having trouble finding a good way to set
up the code so it's clear and robust.
Generally, the behavior is event-driven: e.g.,
when it gets a connection, that kicks off a series of actions.
What complicates it is that each series of actions takes long enough
that it really needs to be in a separate thread, and this thread needs
to die when it reaches the end of the list of actions.
Now, I'm used to the idea that in C++, everything is an object, but
every C++ object needs an owner who is also responsible for
destroying it. Modeling these "action threads" as objects raises the
issue of who owns the object and who will destroy it when its
thread reaches the end of its natural lifespan.
I imagine that this issue arises whenever dealing with threads in
C++, unless the thread is immortal.
What approaches have other people found useful?
It depends somewhat on context. In some cases, I've simply
started the thread, and forgotten about it. Any "thread" object
was somewhere in the system, and not my affair.
More frequently, of course, you need some trace of the thread,
if only to ensure a clean shut-down. (You don't want to return
from main if any threads are still running.) In this case, the
kick-off routine (which has to be extern "C" anyway) deletes the
thread object when the thread function it calls returns.
(Typically, it will also remove it from a list of active
threads; the function triggering the shutdown will wait for the
list to become empty.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]