github.com/alexfalkowski/go-linux/v2/sched controls CPU placement, CPU
scheduling, and block I/O priority for Linux workers. Use it to pin a polling
loop to eligible CPUs or tune the scheduling of a background storage worker.
The package requires Linux 7.0+ and permission to use the selected syscalls.
Linux affinity manual.
Run the work on a dedicated goroutine. Call runtime.LockOSThread before any
related affinity operation and leave the goroutine locked until it exits, so
Go can retire the worker thread. Select CPUs from sched.Affinity() when
narrowing the calling thread’s current set. Inside the dedicated goroutine,
the setup for a synchronous worker can look like this.
runtime.LockOSThread() // Keep the worker locked until it exits.
allowed, err := sched.Affinity()
if err != nil {
return err
}
cpu := allowed.CPUs()[0]
set, err := sched.NewCPUSet(cpu)
if err != nil {
return err
}
if err := sched.SetAffinity(set); err != nil {
return err
}
// Run the work synchronously on this goroutine.
The imports are runtime and github.com/alexfalkowski/go-linux/v2/sched.
Executable examples.
Affinity is per OS thread. Existing sibling threads retain their own masks. An OS thread or child process created by the affected thread can inherit its mask. A new Go goroutine can run on any thread chosen by the Go runtime.
sched.CurrentThreadID() reports the calling OS thread’s numeric ID. Obtain it
from the locked worker before sharing it with a coordinator. On a positive
sched.ThreadID, call Affinity or SetAffinity to address that thread from
another goroutine. Work with the target’s owner to keep it alive until the
operation returns. Linux can recycle the number after exit, and an ID is
interpreted in the caller’s PID namespace.
CPUSet is immutable, with an empty zero value. NewCPUSet accepts logical CPU
IDs 0 through 65535 and folds duplicates. CPUs returns an independent sorted
slice. Copies of the set can be shared across goroutines.
Linux intersects a requested set with CPU availability and cpuset constraints. Query again after setting affinity when the effective set matters. Both the kernel constraints and another writer can change the result between operations. A concurrent cpuset update can also make a set call fail after adjusting the thread’s affinity. The kernel’s effective mask is authoritative.
Out-of-range CPU IDs and explicit thread IDs outside the positive signed
32-bit range match os.ErrInvalid. Syscall errors preserve their Linux errno.
An empty set or a request with no eligible CPU can return EINVAL. A missing
thread returns ESRCH. Setting another thread’s affinity requires matching
credentials or applicable CAP_SYS_NICE and can return EPERM.
Linux 7.0 scheduler implementation.
For hierarchy-wide CPU placement, configure the cgroup cpuset controller. See the design decisions and verification guide.
On the dedicated locked goroutine, call
sched.SetScheduling(sched.Attributes{Policy: sched.Batch, Nice: 10})
to run CPU-intensive background work at a lower time-sharing priority.
sched.Scheduling() reads the calling thread’s parameters. The same operations
on sched.ThreadID address a specific thread.
| Policy | Parameters |
|---|---|
Normal, Batch |
Nice from −20 through 19 and an optional time slice. A zero time slice selects the kernel default. |
Idle |
No additional policy parameters. Returning to another policy may require privilege or a sufficient RLIMIT_NICE. |
FIFO, RoundRobin |
Real-time priority from 1 through 99, with 99 highest. The kernel checks authority and real-time limits. |
Deadline |
CPU runtime, relative deadline, and period as time.Duration. Runtime must be at least 1024 ns and no greater than the deadline. A zero period uses the deadline. Linux checks CPU affinity and admits the request only if bandwidth is available. |
Ext |
Observed policy identity. Use an external sched_ext scheduler to load BPF and configure threads. |
Deadline threads need ResetOnFork to create a child. Otherwise Linux
returns EAGAIN from fork or clone. With the flag set, children of real-time
and deadline threads start with Normal policy and nice zero. For other
policies Linux resets negative nice values to zero. The child also starts
with default utilization clamps and time slice, and with the flag cleared.
Clearing the flag on the parent requires CAP_SYS_NICE.
Linux scheduler fork implementation.
For deadline workloads, Reclaim lets Linux reclaim unused bandwidth and
DeadlineOverrun enables process-directed SIGXCPU overrun notifications.
Set SetUtilMin or SetUtilMax to update the corresponding requested
utilization clamp. Values range from 0 through 1024. ResetUtilization
restores that clamp’s kernel default. A scheduling observation reports the
requested task clamps, which can differ from effective cgroup-constrained
values. It reports only the flags Linux returns. A settings update must
explicitly select which clamps to apply.
Attributes.Size selects the write ABI prefix. Zero uses AttributesV1,
which includes clamps. Use AttributesV0 for the original prefix. A read
reports how many bytes Linux copied into the library’s supported prefix.
Linux errors keep their errno, including EPERM for insufficient authority
and EBUSY when deadline admission cannot reserve the requested bandwidth.
Linux scheduler implementation.
Call sched.SetIOPriority(sched.IOPriority{Class: sched.IOBestEffort, Level: 6})
on the locked storage worker. GetIOPriority reports the thread’s configured
value. The zero priority restores kernel-derived behavior. Best-effort and
real-time I/O each have eight levels with 0 highest. Real-time I/O requires
privilege. The device and I/O scheduler determine how they honor these
settings and any encoded device hint. Sharing a Linux I/O context also shares
the configured priority.
ThreadID.GetIOPriority and ThreadID.SetIOPriority target one thread.
The same methods on an explicit positive ProcessGroupID operate on the
group’s threads. The group read returns the smallest packed effective priority
among accessible threads. Linux compares class first, then hint, then level,
so within a class a smaller hint wins even when its level has lower priority.
A group update can change some threads before returning an error. Coordinate
group lifetime and membership before applying a group update.
Linux I/O priority implementation.
See the executable storage-worker example and real-time verification requirements.