5
votes

I have a C++/MFC application I need to restructure. The app used to process most of the data on the main thread, therefore blocking the input, and now I want to change it so, that all GUI updates are done through PostMessage.

Unfortunately, I can't seem to find a good source on how to achieve this goal.

Right now I'm thinking of creating a priority queue, protected with critical section, a worker thread (while(true)) that processes this queue, and PostMessage mechanism that sends pointers to data to main thread.

What scares me with this approach is that PostMessage is not guaranteed to arrive at the main thread at all, so, if I understand correctly, there is a chance of memory leak.

The second problem is that another app can send a custom message to my application, and my application might try to dereference the WPARAM or LPARAM as a pointer thereby causing AV.

Does anyone know what are the best practices for such tasks?

The data can be HTML content for web control, or other content for listboxes, dropdowns, etc.

3
" PostMessage is not guaranteed to arrive at the main thread at all" Huh?John Dibling
Does data need to go from the main thread -> the worker thread, from the worker thread -> the main thread, or both?John Dibling
If I understand correctly, then if the MessageQueue exceeds 10,000 messages, could be 4,000 with modified registry, then something bad can happen. Can't find what exactly though.Coder
Mostly worker -> main. The other direction can be covered with simple parameters.Coder
@Madman: ah, yes you're correct there is a hard limit on the windows message queue size. But if you're bumping up against that, you really should take a look at why. You're app's not going to get any idle time, will grind to a halt, won't update the screen, and all sorts of bad stuff happens.John Dibling

3 Answers

11
votes

Your messages will get there. I'm not sure why you think PostMessage isn't guaranteed to work -- it is. (EDIT: Assuming PostMessage() returns TRUE! Check your return codes!)

You want to avoid using a queue to communicate data between the threads. Any queue that is accessed by both threads will need to be protected. Adding hard locks on both sides will serialize your application.

Instead, create a data structure on the heap using new that contains your data, then tell the other thread "I;ve got data for you, and here it is." The recieving thread then takes ownership of that data pointer, and is responsible for deleteing it. Doing it this way, there are no hard locks.

Now the only trick is figuring out the "tell the other thread" part, but that's easy too.

If you're sending data from the worker thread to the main thread, just use PostMessage():

worker_thread_proc()
{
// ..

  // Create the data object you're going to pass to the MT
  MyData* data = new MyData;
  data->some_value_ = "foo";

  // Pass it:
  PostMessage(main_wnd, WM_YOU_HAVE_DATA, reinterpret_cast<WPARAM>(data), 0);
}

...the main thread processes this, then deletes the data:

MainWnd::OnYouHaveData(WPARAM wp, LPARAM)
{
  std::auto_ptr<MyData> data(reinterpret_cast<MyData*>(wp));
  my_widget->set_text(data->some_value_); // you get the idea
}

If you're worried about external apps's custom messages bumping in to yours, you can get Windows to give you a unique message ID using RegisterWindowsMessage() -- your only challenge here is picking the right name for your message.

If your sending data from the main thread to the worker thread, you can do the same as above, except instead of using PostMessage() to send the data over the wall, you can use either QueueUserAPC() (making sure your worker thead is in an alertable wait state -- read the remarks in the linked docs) or PostThreadMessage().

EDIT:

Per your comments in the OP, now I understand why you're concerned about PostMessage() not working.

Yes, there is a hard limit to the Windows message queue size. By default, there can be only 4,000 messages in the queue. (registry settings can adjust this up to a max of 10,000).

If the queue is full, any call toPostMessage() will fail with an error code. When you check GetLastError() (I don't remember which error code it returns right now) it will be clear that the message queue is full.

Not to sound like a mother hen, but you really need to check your return values from API calls. But beyond that, if you are running in the the message queue ceiling, I'd say your application is broken anyway. When the queue is full, your application won't be able to breathe. The screen won't paint, any processing you do will be stale, and all kinds of bad things happen. If this is the situation you're in, you may need to look at why.

2
votes

Use two queues, one for work requests going to the worker thread and one for results going back to the main thread. You can use PostMessage to wake up the main thread and tell it to check the queue, but you won't need any parameters in the message.

1
votes

I solved a similar problem some time ago. I made a singleton queue to hold the data (or actions) that need to flow from background threads to the UI (main) thread. The queue is protected by a critical section. Background thread would place its data in the queue and post a message. The message does not hold any data, it acts as a simple wake-up call "hey, main thread, look at the queue, there's work for you".

This way, you don't risk leaking any memory or other resources; the queue can be safely destroyed with all the data it contains.