Home > front end >  Avoiding wasted CPU cycles while waiting for input
Avoiding wasted CPU cycles while waiting for input

Time:03-23

My program is waiting for the F4 hotkey to be pressed in order to exit.

I am calling Sleep(1) because without this, I am using 18% of my CPU. Is this the correct way to do this? My gut is telling me there is a better way.

I know that keyboard inputs are interrupt-based, but is there any way to make a thread sleep until a keyboard state change is registered?

#include <Windows.h>
#include <iostream>
#include <thread>

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {

    while (!(GetAsyncKeyState(VK_F4) >> 15)) {
        Sleep(1);  // Sleep for 1 ms to avoid wasting CPU
    }
    return 0;
}

CodePudding user response:

Look into RegisterHotKey, UnRegisterHotkey, GetMessage, TranslateMessage and DispatchMessage like

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow)
{

    RegisterHotKey(0, 1, MOD_NOREPEAT, VK_F4);
    MSG msg;
    while (GetMessage(&msg, 0, 0, 0) != 0)      // TODO: error handling
    {
        if (msg.message == WM_HOTKEY)
        {
            if (msg.wParam == 1) {
                break;
            }
        }
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    UnregisterHotKey(0, 1);
    return 0;
}

GetMessage() will block until it receives a window message, which wakes it up. Get a copy of Process Explorer, look into the process details and see it not using a single CPU cycle while it's waiting.

  • Related