1

I'm using a dispatching mechanism in my Win32 application where non-main threads can post a piece of work wrapped in an std::function for later execution on the main thread. This is realized by creating a hidden window from the main thread, and using its window procedure to filter out these pieces of work, and then executing them. Background threads then use a PostMessage() call on this window, with a custom message id (>WM_USER), while wrapping a heap-allocated std::function in the LParam.

This approach appears to be conceptually sound, but I have some reservations regarding thread-safety. MSDN makes no mention that I found, indicating whether multiple threads may or may not simultaneously post a message to the same window. Is there a definitive verdict?

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 2
    Posting (or sending) messages across threads is safe. – IInspectable May 18 '22 at 21:58
  • This is a perfectly safe approach for serializing functions. To avoid leaks, just make sure you free the `function` objects after you are done using them, including if `PostMessage()` fails to post (many beginners forget that step!). Also, make sure you don't destroy the window after `PostMessage()` is called and before its message is dispatched, otherwise you will leak, so shut down all of your posting threads before destroying the window. – Remy Lebeau May 18 '22 at 22:17
  • @RemyLebeau Good advice, but they could conceivably still be in transit on a busy system. (And I'm not sure how best to handle that.) – Paul Sanders May 18 '22 at 22:40
  • 1
    @pau `PostMessage` will not return before the message has been enqueued. If you're shutting down all senders prior to destroying the receiver, there is no opportunity for a message to *"be in transit"*. – IInspectable May 18 '22 at 23:00
  • @IInspectable OK, but what happens if you destroy the receiver while there are still messages in the queue? – Paul Sanders May 18 '22 at 23:39
  • @pau `PeekMessage` will tell you whether the message queue is empty so that you don't have to. – IInspectable May 18 '22 at 23:50
  • @IInspectable Ah yes, silly me. I even use that trick myself! – Paul Sanders May 18 '22 at 23:51
  • @PaulSanders yeah, so just shut down the senders, then pump the message queue until there are no more pending messages, then finish the rest of your shutdown – Remy Lebeau May 19 '22 at 00:06
  • @RemyLebeau I've stayed up way too late! I do exactly that in my own code (facepalm emoji). – Paul Sanders May 19 '22 at 00:14

0 Answers0