How to set process priority in C ++

I am working on a program to sort data, and I need to set the process to priority 31, which, in my opinion, is the highest process priority on Windows. I did some research, but can't figure out how to do this in C ++.

+7
source share
3 answers

Calling the Windows API SetPriorityClass allows you to change the priority of the process, see the example in the MSDN documentation and use REALTIME_PRIORITY_CLASS to set the highest priority:

SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS) 

Note : if you request true priority in real time, you will receive it. This is a nuclear weapon. The OS will mercilessly prioritize the priority stream in real time, much higher than even processing input at the OS level, flushing the disk cache and other high-priority tasks that are time-critical. You can easily lock your entire system if a thread in real time depletes your processor. Be careful with this, and if this is not absolutely necessary, consider using high priority. Additional Information

+8
source

The following function will do the job:

 void SetProcessPriority(LPWSTR ProcessName, int Priority) { PROCESSENTRY32 proc32; HANDLE hSnap; if (hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)); if (hSnap == INVALID_HANDLE_VALUE) { } else { proc32.dwSize = sizeof(PROCESSENTRY32); while ((Process32Next(hSnap, &proc32)) == TRUE) { if (_wcsicmp(proc32.szExeFile, ProcessName) == 0) { HANDLE h = OpenProcess(PROCESS_SET_INFORMATION, TRUE, proc32.th32ProcessID); SetPriorityClass(h, Priority); CloseHandle(h); } } CloseHandle(hSnap); } } 

For example, to set the priority of the current process below normal, use:

 SetProcessPriority(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS) 
+3
source

After (or before) SetPriorityClass, you must set the priority of an individual thread to achieve the maximum possible. In addition, a different security token is required for the real-time priority class, so be sure to grab it (if available). SetThreadPriority is the secondary API after SetPriorityClass.

+1
source

Source: https://habr.com/ru/post/1342583/


All Articles