cwindowswinapisleepmessage-loop

How can I ensure that a Message Loop in Win API doesn't use the CPU when no messages available?


How can I ensure that a Message Loop in Win API doesn't use the CPU when no messages are available? In other words, I effectively want a Message Loop which says "Sleep until I have a new message".

I've tried looking this up, and it's very hard to determine clear examples. The WinAPI is very different than the POSIX APIs where there's an explicit sleep and SIG handler to wake up. Complicating things is that looking up example code makes it hard to distinguish true syscalls / kernels from library calls to wrappers.


Solution

  • I've tried looking this up, and it's very hard to determine clear examples.

    This is the simplest form of a message loop:

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        DispatchMessage(&msg);
    }
    

    The documentation for GetMessage explains its behavior:

    GetMessage blocks until a message is posted before returning.

    It doesn't consume resources until there's some work to do. You'll find exhaustive coverage of the underlying principles here: About Messages and Message Queues.