Window message queue is not generic data structure

Today I would like to talk about window message queue. Many developers for Microsoft windows familiar with this subject. There are many books about this subject and honestly, I was under impression that each window has own message queue. I even asked many developers around me and most developers were telling the same story. Some believe that there is one message queue for process and some even believe that there is one queue for whole session.

Today I will try to get to bottom of this. If we read here you will see this: “The system maintains a single system message queue and one thread-specific message queue for each GUI thread”. Just to be clear GUI thread is thread that calls some message related functions. Anyway, so it looks like all windows that created in the same thread will share the same message queue.

But I decided to check it. Easiest way to do this is to create two windows, then post messages in first window until it fails and then try to post message to second window. If these windows have own message queue, then post to second window will succeed. If they share message queue, then it will fail. I will not provide code for this because C code will be really long and boring and using some framework will not be easy to understand by people who are not familiar with that framework. But in essence you will create two windows and will have two window handles: handle1, handle2. Then call PostMessage like this:

while(PostMessage(handle1, WM_USER, 0, 0));
if(PostMessage(handle2, WM_USER, 0, 0))
  // success
  // failure

And as correctly stated in link I provided it turns out that post to second window failed and it means that all windows created in the same thread actually share the same message queue.

What are implications of this? Imaging you decided that you will use message queue to post work items to it using PostMessage and then process it later. And this will be not the best idea if there are a lot of work items. Message queue is 10000 deep and as we just discovered shared by all windows in that thread. And if you have multiple windows and you post messages to them, then it should be well below 10000 combined at the same time. Remember window message queue designed for different purpose. Do not try to be lazy and cut corners. It will fail at moment when you expect it least. It is really hard to find and to debug it. Trust me!