doucong3048 2015-05-07 10:18
浏览 83
已采纳

如何在Windows中使用Go将进程设置为CPU?

I want set a process to a CPU using Go in win7, the below code:

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)
    }
}

When I use go run affinity.go, get the follow info:

# 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

I find SYS_SCHED_SETAFFINITY that it only used in linux. So, I want to set a process to a cpu using Go in Windows(Win7), what can I do?

  • 写回答

1条回答 默认 最新

  • douqiao1413 2015-05-07 10:54
    关注

    You'll have to invoke the WinAPI SetProcessAffinityMask.

    Something like this should work:

    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 being the process handle, and mask being the desired affinity mask, of course.

    This is taken from Go benchmarks, under the BSD license.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料