Re: Multithreading questions
Dave Cullen wrote:
I'm considering using a worker thread to control machinery in a dialog based
application. The task will be repetitive, lasting about 1 second every 3 or
My questions are these:
From what I've read, the worker thread must return or call AfxEndThread from
within itself. What happens if the main thread terminates first? Does the
worker thread keep running?
If the machine hangs and the user is forced to do something ugly like
CTRL-ALT-DEL does that kill both threads?
I can either allow the worker thread to run continuously and communicate
through synchronization objects, or run and terminate each time it's needed.
What's the preferred method and the tradeoffs for these choices?
You should design an orderly shutdown sequence to make sure the worker
thread stops its task cleanly and safely.
1. When the program is closing (typically, at the WM_CLOSE request) it
should signal worker threads to exit. The program should not close at
this point so it will not destroy information that might be accessed by
the worker threads. Main thread should wait for events or messages
indicating that all workers have closed.
2. Worker threads process the close signal, freeing memory, handles,
etc. and then returning from the thread function.
3. Only then is it safe for the main thread to continue its shutdown
sequence, doing the normal WM_CLOSE processing.
Structuring the worker thread as a continuous loop, with a
WaitForMultipleObjects call inside the loop, is much more efficient.
(Thread creation is quite expensive. Thread resumption is quite cheap.)
Scott McPhillips [VC++ MVP]