Search code examples
cwindowsmultithreadingsleepthread-priority

Command prompt window priority on Windows Server 2008 R2 (Windows 7)


Is an application running in a console window treated "less important" by the windows scheduler, i.e. does Windows allow it to "sleep" longer if it's minimized? I thought I read something about Windows lowering its priority if it's minimized, but perhaps I just mixed something up.

The thing is, I have a C console app (written in VS2015, but running on Windows Server 2008 R2, so no GetSystemTimePrecise support, unfortunately), which does some socket communication, but sometimes the receiving threads (IOCP) get paused and packets get merged together.

So, in my main function I wrote something like this:

 timeBeginPeriod(1);

while (true)
{
    QueryPerformanceCounter(&start);
    Sleep(1);
    QueryPerformanceCounter(&stop);
    LogTimeElapsed(start, stop);
}

I obviously didn't expect to get millisecond accuracy out of Sleep(1), but I was surprised to get numerous delays of ~50 milliseconds, with maximum reaching more than 120 milliseconds on several occasions.

Of course, during this time, there were other active processes consuming CPU (doing some database exporting and similar, with total CPU going to ~50%), but since this is a quad core CPU I thought that the thread scheduler would still prevent such long delays from happening.

Is this an artifact of running as a plain console app, or should I expect similar delays in any Windows desktop/service application?


Solution

  • Windows is not a real time system, so it is allowed to suspend a task for a non deterministic time. If other tasks use the 4 cores during a short time (some tenths of seconds) any program (be it console of GUI) can be suspended for that time. And as Windows is a feature rich OS, many system services can compete for the CPU in addition to other tasks, so latencies up to few tenths of seconds can be expected at any time

    Simply the TCP stack guarantees that the program will get all the data received during that time in correct order, but it is allowed to concatenate several packets in on single read because TCP is a stream protocol. So you program should be prepared for that. The only alternative is to use a real time OS, either on the main machine or on a dedicated one.