How to minimize cpu usage in a thread created by _beginThreadEx?

118 Views Asked by At

I have a Windows app that simply runs in the background and watches constantly for data appearing on stdin by means of a separate thread. It does this because it is a Chrome native messaging host and that's how it is expected to communicate with the browser extension (as is clarified in this SO question by RobW). It seems to run fine although imo it uses too much of the cpu when there is no activity. When the browser extension sends bytes on stdin to my app it has to be discovered and processed immediately, and because the processing is intensive an increased demand for cpu usage is understandable, but seems it should not use much when there is no activity.

Disclaimer: I would not call myself an experienced Windows developer.

I am using _beginThreadEx() to launch the function that reads constantly from stdin. The thread is created in InitInstance() like so:

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   int nStdInDescriptor = _fileno(stdin);
   hStdIn = (HANDLE) _get_osfhandle(nStdInDescriptor);

   OutputDebugStringA("starting message processing thread function");
   hReadInputThread = (HANDLE)_beginthreadex(0, 0, &threadfunc_processMessages, &i, 0, 0);

   hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd && !hReadInputThread)
   {
      return FALSE;
   }

   hMainWnd = hWnd;

   return TRUE;
}

and

unsigned int __stdcall threadfunc_processMessages(void* data)
{
    char buffer_temp[STDIN_BUF_SIZE];
    buffer_main = NULL;

    DWORD dwNumBytesRead;
    DWORD dwNumBytesToRead = STDIN_BUF_SIZE;

    while (1) {

        if (ReadFile(hStdIn, buffer_temp, dwNumBytesToRead, &dwNumBytesRead, NULL)) {
            OutputDebugStringA( "Found some bytes on stdin" );

            // byte processing code here. it always processes normally
        }
    }

    return 0;
}

Task Manager shows cpu usage around 49%. I assumed _beginThreadEx() would run in the background, yet still be responsive since it needs to pounce on any data that shows up on stdin. Any help is appreciated.

0

There are 0 best solutions below