Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set CPU affinity in Go

I'm using isolcpus to assign a subset of the total CPU cores only for kernel tasks. This means that I can use the reminder for other tasks. I noticed when I run the tests/benchmarking tool from go, all the kernel processors are used (using htop). However, when I use taskset -c 3-10 go test -bench ., only one CPU core shows that is running the command. I was expecting the workload to be distributed to cores 3-10. Is it possible to achieve this?

Update: Thanks to @JimB for suggestion: I'm running the following golang code on the cpus cores reserved for kernel cores using taskset and works fine. But when scheduling outside those cores only one cpu core is used instead of the entire range specified in taskset.

package main

import (
    "fmt"
    "golang.org/x/sys/unix"
    "testing"
    "time"
)


func TestSchedSetaffinity(t *testing.T) {

    var newMask unix.CPUSet
    newMask.Set(0)

    err := unix.SchedSetaffinity(0, &newMask)
    if err != nil {
            fmt.Printf("SchedSetaffinity: %v", err)
    }

    for i := 0; i < 50; i++ {
            fmt.Println("Hello world")
            time.Sleep(2 * time.Second)
    }
}
like image 973
Andrei Avatar asked Dec 01 '25 02:12

Andrei


1 Answers

isolcpus does not work well with taskset and go. To take advantage of all allocated cpu cores you need to use chrt.

For example:

taskset -c 3-10 chrt 1 ./my_go_workload_binary

The assumption is that the cpu cores 3-10 in the isolcpus set.

like image 86
Andrei Avatar answered Dec 02 '25 16:12

Andrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!