如何使用Windows中的Go设置进程到CPU?

时间:2015-05-07 10:18:35

标签: windows go

我想在win7中使用Go设置进程到CPU,代码如下:

package main

import (
    "fmt"
    "math"
    "runtime"
    "syscall"
    "unsafe"
)

func SetAffinity(pid int, mask *int64) {
    syscall.Syscall(syscall.SYS_SCHED_SETAFFINITY,
        uintptr(pid), 8, uintptr(unsafe.Pointer(mask)))
}

func GetAffinity(pid int, mask *int64) {
    syscall.Syscall(syscall.SYS_SCHED_GETAFFINITY,
        uintptr(pid), 8, uintptr(unsafe.Pointer(mask)))
}

var cpuNum = float64(runtime.NumCPU())

var setx = []struct {
    args     int
    expected int64
}{
    {0, int64(math.Pow(2, cpuNum)) - 2},
}

func main() {
    for _, ca := range setx {
        var cpuSet int64
        GetAffinity(ca.args, &cpuSet)
        cpuSet = cpuSet & 0XFFFFFFE
        SetAffinity(ca.args, &cpuSet)
        fmt.Println(cpuSet)
        GetAffinity(ca.args, &cpuSet)
        fmt.Println(cpuSet)
    }
}

当我使用go run affinity.go时,请获取以下信息:

# command-line-arguments
.\affinity.go:12: undefined: syscall.SYS_SCHED_SETAFFINITY
.\affinity.go:13: not enough arguments in call to syscall.Syscall
.\affinity.go:17: undefined: syscall.SYS_SCHED_GETAFFINITY
.\affinity.go:18: not enough arguments in call to syscall.Syscall

我发现它只在linux中使用SYS_SCHED_SETAFFINITY。 所以,我想使用Go in Windows(Win7)将进程设置为cpu,我该怎么办?

1 个答案:

答案 0 :(得分:2)

您必须调用WinAPI SetProcessAffinityMask

这样的事情应该有效:

func setProcessAffinityMask(h syscall.Handle, mask uintptr) (err error) {
    r1, _, e1 := syscall.Syscall(syscall.NewLazyDLL("kernel32.dll").NewProc("SetProcessAffinityMask").Addr(), 2, uintptr(h), mask, 0)
    if r1 == 0 {
        if e1 != 0 {
            err = error(e1)
        } else {
            err = syscall.EINVAL
        }
    }
    return
}

h是进程句柄,当然mask是所需的亲和力掩码。

这是根据BSD许可证从Go benchmarks获取的。