HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Asking Windows for real-time priority

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
priorityrealtimeforwindowsasking

Problem

This code snippet is about asking Windows for the highest possible execution priority. Basically, we have to ask for real-time priority class for the entire process, after which each thread has to ask for real-time thread priorities. However, since Windows Vista, whatever is the program that needs the real-time priority, it must be asked to be run in administrator privilege level.

The demonstration program I provide simply loops for 7 seconds. During that period, your system should be frozen (try pressing Caps Lock; should not switch the Caps Lock light). Also, if you put on some audio, the sound card will repeat its contents of the sound buffer over and over again.

rtprio.h:

#pragma once
#include 

BOOL RealTimePriorityClass()
{
    return SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
}

BOOL RealTimeThreadPriority()
{
    return SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
}


main.cpp:

```
#include
#include "rtprio.h"

static const DWORD dwInterval = 7000; // millseconds.

DWORD WINAPI ThreadProc(LPVOID lpParams);

int WINAPI WinMain(HINSTANCE hInst,
HINSTANCE hPrev,
LPSTR lpCmdLine,
int nShowCmd)
{
DWORD i;
DWORD dwInitTicks;
DWORD dwCores;
SYSTEM_INFO sysInfo;

GetSystemInfo(&sysInfo);
dwCores = sysInfo.dwNumberOfProcessors;

// Ask real-time priority class for the entire process.
RealTimePriorityClass();

for (i = 0; i < dwCores - 1; i++)
{
CreateThread(NULL,
0,
ThreadProc,
NULL,
0,
NULL);
}

RealTimeThreadPriority();

dwInitTicks = GetTickCount();

while (GetTickCount() - dwInitTicks < dwInterval);

return 0;
}

DWORD WINAPI ThreadProc(LPVOID lpParams)
{
// Ask for real-time priority for this thread.
RealTimeThreadPriority();

// Freeze the system for dwInterval milliseconds.
while (TRUE) {

Solution

Works as intended.

But I get a thread priority of 15 rather than the expected 31 for a REALTIME_PRIORITY_CLASS?

See SetThreadPriority.

It seems that the THREAD_PRIORITY_TIME_CRITICAL is defined to THREAD_BASE_PRIORITY_LOWRT - 1, which could be further elevated to 31 if needed.

Context

StackExchange Code Review Q#108758, answer score: 3

Revisions (0)

No revisions yet.