[go]如何在 golang for mac 中设置进程(由操作系统线程继承)的优先级?
· 收录于 2024-01-06 07:53:07 · source URL
问题详情
如何在 golang for mac 中设置进程(由操作系统线程继承)的优先级? 系统调用。SetPriority 与 syscall 一起使用。PRGRP 标志设置进程的优先级,并由 ubuntu 上的线程继承。Mac有类似的方法吗?我们如何从 golang 访问苹果 qos?
程序在 ubuntu 上运行,但在 mac 上不起作用
package main
import (
"fmt"
"os"
"runtime"
"sync"
"syscall"
"time"
)
func main() {
// runtime.GOMAXPROCS(5)
// Get the current process ID
pid := os.Getpid()
fmt.Printf("Current Process ID: %d\n", pid)
// Set process priority to the lowest
setProcessPriority(pid, syscall.PRIO_PGRP, 10)
// Number of goroutines to spawn
numGoroutines := 100
// Use a wait group to wait for all goroutines to finish
var wg sync.WaitGroup
wg.Add(numGoroutines)
start := time.Now()
// Spawn goroutines
for i := 0; i < numGoroutines; i++ {
go func(id int) {
defer wg.Done()
fmt.Printf("Goroutine %d started.\n", id)
cpuIntensiveWork()
fmt.Printf("Goroutine %d completed.\n", id)
}(i)
}
// Wait for all goroutines to finish
wg.Wait()
elapsed := time.Since(start)
fmt.Printf("All goroutines completed in %f\n.", elapsed.Seconds())
}
func setProcessPriority(pid int, which int, priority int) {
if runtime.GOOS == "windows" {
fmt.Println("Setting process priority is not supported on Windows.")
return
}
// Set process priority for Unix-like systems
err := syscall.Setpriority(which, pid, priority)
if err != nil {
fmt.Println("Error setting process priority:", err)
}
}
func cpuIntensiveWork() {
// Simulate CPU-intensive work
for i := 0; i < 100000; i++ {
for j := 0; j < 10000; j++ {
_ = j * j
}
_ = i * i
}
}
最佳回答
您的程序在 Linux 和 macOS 上对我来说失败了。问题在于你对 syscall 的使用。PRIO_PGRP
您应该在哪里使用 syscall。PRIO_PROCESS
。我将您的程序简化为以下内容,它在 Linux 和 macOS 上按预期工作。
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
pid := os.Getpid()
fmt.Printf("Current Process ID: %d\n", pid)
prio, err := syscall.Getpriority(syscall.PRIO_PROCESS, pid)
if err != nil {
fmt.Println("Error getting process priority:", err)
}
fmt.Println("Original priority:", prio)
if err := syscall.Setpriority(syscall.PRIO_PROCESS, pid, 10); err != nil {
fmt.Println("Error setting process priority:", err)
}
prio, err = syscall.Getpriority(syscall.PRIO_PROCESS, pid)
if err != nil {
fmt.Println("Error getting process priority:", err)
}
fmt.Println("New priority:", prio)
}
在 macOS 上:
在 Linux 上:
$ go run x.go
Current Process ID: 117032
Original priority: 20
New priority: 10
如果更改系统调用。PRIO_PROCESS
到系统调用。PRIO_PGRP
,您将在两个平台上看到如下错误:
Current Process ID: 113604
Error getting process priority: no such process
Original priority: -1
Error setting process priority: no such process
Error getting process priority: no such process
New priority: -1