Re: Object model for self-terminating "threads"
On 1/31/07 12:23 AM, in article
firstname.lastname@example.org, "Alan McKenney"
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.
Then why not implement the thread's entry procedure along these lines:
int MainProc( void * userData)
return 0; // good-bye
The thread ends once it returns from the routine where it started executing.
For a more complicated sequence of actions, you could implement the thread
as a state machine (possibly using a parser- or lexer-generating program).
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.
Not every aspect of a program resembles an object. For example, how is a
thread of execution like an "object"? Where is its data, where are its
routines? It seems to me that executing a series of operations sequentially
is an example of "procedural" programming, than of "object-oriented"
I imagine that this issue arises whenever dealing with threads in
C++, unless the thread is immortal.
What approaches have other people found useful?
Don't have the program spawn threads, have it spawn processes instead. Then
implement the thread's operations as a simple, single-threaded program. In
fact, compared to writing multi-threaded code, writing multi-process code is
so embarrassingly easy - that it seems almost immoral.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]