英文:
How set process to a CPU using Go in windows?
问题
我想在Windows 7中使用Go语言将进程绑定到CPU。以下是代码:
package main
import (
"fmt"
"runtime"
"syscall"
"unsafe"
)
func SetAffinity(pid int, mask *int64) {
// 在Windows中设置进程绑定的CPU
// 这里需要使用Windows API来实现
// 可以使用syscall.SetProcessAffinityMask函数来设置进程的亲和性掩码
}
func main() {
// 在这里调用SetAffinity函数来设置进程绑定的CPU
}
在Windows中,你可以使用syscall.SetProcessAffinityMask
函数来设置进程绑定的CPU。你需要将进程的句柄和亲和性掩码作为参数传递给该函数。具体的实现细节可以参考Windows API文档或者相关的Go语言库。
英文:
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
得分: 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
是所需的亲和性掩码。
这段代码摘自Go的基准测试,使用的是BSD许可证。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论