How to set CPU affinity in Go

3.2k Views Asked by At

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

There are 1 best solutions below

0
On

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.