Home Forum RSS PGP Alerts Links (D) |
|
Multithreading class with message queue Comment on this articleMultithreading with message queue requires not only the usual multithreading function calls and structures, but also the creation and maintenance of message queues. The whole idea here is to have the thread class use regular windows message queues to receive requests from other threads. All this can be done using so-called user interface threads in MFC, but with at least two major drawbacks: a window handle is needed. And MFC is needed. Which makes using the stuff under MTS or in an NT service a bit difficult. (You still need the multithreading runtime library, of course.) It's not really necessary to have a window or a window procedure to receive windows messages. All you need is a thread (and to know its "thread ID") and a pre-allocated windows message queue. Such a queue is set up for you by Windows if your thread has a window associated with it, but it's almost as easy to get one if you don't have a window, simply by accessing the message queue with, for example, PeekMessage before anyone tries to post messages to it. Take a look at the run() member function in the thread class (file thread.h). There you'll see a call to PeekMessage(...) followed by a call to SetEvent(...). The idea here is that PeekMessage(...) can take a little while to get the message queue created and only when that has happened really and fully does the program drop through to the SetEvent(...) which (if you take a glance at the WaitForSingleObject(...) call in the start() member function) allows the client to proceed with life. To actually use the class, you have to derive from thread and implement a TakeMsg(...) method that does something with the received messages. See the main.cpp file in the archive for a trivial example. Note that you don't need to handle the WM_QUIT message; that is provided for in the thread base class. Sending messages to a thread is done by calling the PostMsg(...) member function. Terminating a thread is done by calling the stop() function. Note that calling the PostMsg(...) function with WM_QUIT as parameter would also work, but would cause race-conditions since the caller will not wait for the thread to actually close down.
|
TOP |