Which is faster: SetEvent, SendMessage, PostMessage

cpostmessagesendmessagewinapi

Environment: Win32, C/C++

All three (3) can be used for a thread to signal to main() that it has completed an operation for example.

But which one is the fastest signal of all?

hmm…

Best Answer

All three options require a thread context switch to actually signal the receiving thread. It's quite likely that the overhead of the context switch will overwhelm any difference in processing cost in any of the APIs.

The choice is likely best driven by the nature of the receiving thread, e.g. is it a UI thread, and/or does it carry out a message loop. That said, some fine detail includes:

  • SendMessage is useful when the receiving thread is a UI thread, churning inside a message loop. The sending thread will block until the recipient processes the message. But it may handle unqueued messages during that time. That logic could potentially slow things down, as additional context switches may be involved, making SendMessage the slowest of the three.

  • PostMessage is also useful when the recipient is inside a message loop. The difference from SendMessage is that it doesn't wait for the recipient to process the message, thus incurring less overhead.

  • SetEvent is useful when the receiving thread can wait on an event object, e.g. with WaitForSingleObject(). It incurs no marshaling or message processing overhead, and is likely to respond quicker than the others.