admin管理员组

文章数量:1389754

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.

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.

Share Improve this question edited Mar 14 at 14:28 TylerH 21.1k79 gold badges79 silver badges114 bronze badges asked Mar 13 at 22:14 SRobertJamesSRobertJames 9,20516 gold badges70 silver badges123 bronze badges 11
  • 2 I am not sure what you seek. The standard message loop shown in MS sample code does not look special to me learn.microsoft/en-us/windows/win32/winmsg/… and GetMessage is a blocking call you don't need signals. – Robert Commented Mar 13 at 22:25
  • 3 “ GetMessage does not return until a message matching the filter criteria is placed in the queue.” learn.microsoft/en-us/windows/win32/winmsg/… – Raymond Chen Commented Mar 13 at 22:37
  • 1 Both of the "questions" seem to have an answer that is "ask Raymond Chen". I'm tempted to vote to close. – pmacfarlane Commented Mar 14 at 0:21
  • 3 You're telling us about a problem that only exists in your head. Not an actual problem you've found. If I'm wrong, show us the code and ask about it. – pmacfarlane Commented Mar 14 at 0:37
  • 2 @pmacfarlane no need even to ask me. I just quoted the documentation – Raymond Chen Commented Mar 14 at 1:59
 |  Show 6 more comments

1 Answer 1

Reset to default 4

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.

本文标签: