如何在Golang中以编程方式将进程(应用程序)优先级从Normal更改为Low

eqzww0vc  于 2023-05-11  发布在  Go
关注(0)|答案(2)|浏览(132)

如何在Golang中编程更改进程优先级类?
我有CPU密集型任务,我希望系统和用户程序有更高的优先级,所以我的Golang应用程序只在系统空闲时运行,或者更好地使用空闲的CPU内核。
就像这样

System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle;

https://stackoverflow.com/questions/10391449/set-process-priority-of-an-application但是在Golang。
先谢了

2lpgd968

2lpgd9681#

进程的调度优先级是一个依赖于操作系统和平台的设置,所以你可能想看看syscall包:

func Setpriority(which int, who int, prio int) (err error)

这在Linux上工作。

dbf7pr2w

dbf7pr2w2#

在Windows上工作的示例程序:

package main

import (
    "log"
    "os/exec"

    "golang.org/x/sys/windows"
)

// https://learn.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights
const PROCESS_ALL_ACCESS = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xffff

func SetPriorityWindows(pid int, priority uint32) error {
    handle, err := windows.OpenProcess(PROCESS_ALL_ACCESS, false, uint32(pid))
    if err != nil {
        return err
    }
    defer windows.CloseHandle(handle) // Technically this can fail, but we ignore it

    err = windows.SetPriorityClass(handle, priority)
    if err != nil {
        return err
    }

    return nil
}

func main() {
    cmd := exec.Command("python", "hello.py")
    err := cmd.Start()
    if err != nil {
        log.Fatal(err)
    }

    // Set priority to above normal
    err = SetPriorityWindows(cmd.Process.Pid, windows.IDLE_PRIORITY_CLASS)
    if err != nil {
        log.Fatal(err)
    }

    err = cmd.Wait()
}

相关问题