Windows has a simplified built-in mechanism for communication among threads, using message loops. APIs such as
PeekMessage() can be used to achieve this. E.g.,
BOOL bRet = GetMessage(
Once the loop is setup, use
PostThreadMessage() to send the message across. E.g.,
In fact, message based communication is the building block of Windows. Of course, it has serious security implications as the source of the message is not known to the receiver, but that's a topic for another article.
In this article, I used this concept and the MFC macro style message handler declaration and wrapped them in a class that lets you send messages in two different modes:
SendMessage with timeout
In order to construct the message loop, I used
GetQueuedCompletionStatus() instead of the above mentioned method. The reasons for this are as follows:
IoCompletionPorts are fast and less resource intensive.
- No restriction as in the other methods where the thread needs to belong to the same desktop, etc.
OK, let's see an example. By the way, the attached files have a Visual Studio based project that you can compile and run. Check the
First, derive a class from
class DemoThread : public MsgThread
ON_MSG(kMsgGoGetPizza, OnMsgGoGetPizza )
Elsewhere in your code:
And that's it. Just be careful; if you use
SendMessage, you might end up in a deadlock if you haven't designed things properly.
Just include MsgHandler.[h,cpp] and MsgThread.[h,cpp] in your project. I hope you find it useful. Any comments or suggestions are most welcome.