How to set the process priority in C++

一笑奈何 提交于 2019-12-04 04:24:58
lunixbochs

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

SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS)

Caution: if you are asking for true realtime priority, you are going to get it. This is a nuke. The OS will mercilessly prioritize a realtime priority thread, well above even OS-level input processing, disk-cache flushing, and other high-priority time-critical tasks. You can easily lock up your entire system if your realtime thread(s) drain your CPU capacity. Be cautious when doing this, and unless absolutely necessary, consider using high-priority instead. More information

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 to below normal, use:

SetProcessPriority(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS)

After (or before) SetPriorityClass, you must set the individual thread priority to achieve the maximum possible. Additionally, another security token is required for realtime priority class, so be sure to grab it (if accessible). SetThreadPriority is the secondary API after SetPriorityClass.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!