cpus

package module
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2026 License: Apache-2.0 Imports: 12 Imported by: 2

README

CPUs

PkgGoDev GitHub build and test Coverage Go Report Card

cpus is a small Go module for dealing with CPU lists and sets, as used throughout several places in Linux, such as syscalls and inside procfs pseudo files. It has been carved out from the lxkns project as it is useful in applications, tools, and tests beyond lxkns.

Please refer to the module documentation for usage and details.

Tinkering

When tinkering with the cpus source code base, the recommended way is a devcontainer environment. The devcontainer specified in this repository contains:

  • gocover command to run all tests with coverage, updating the README coverage badge automatically after successful runs.
  • Go package documentation is served in the background on port TCP/HTTP 6060 of the devcontainer.
  • go-mod-upgrade
  • goreportcard-cli.
  • pin-github-action for maintaining Github Actions.

cpus is Copyright 2024‒25 Harald Albrecht, and licensed under the Apache License, Version 2.0.

Documentation

Overview

Package cpus supports working with CPU lists and sets, as well as querying the CPUs currently assigned to processes and tasks and pinning tasks and processes to specific CPU sets.

Logically, List and Set are equivalent, as they both represent sets of one or more logical CPUs. Each logical CPU is identified by their 0-based CPU number. The difference between List and Set lies in their internal representations, mirroring different representation forms in the Linux syscalls and procfs pseudo files.

  • List internally stores CPU numbers as ranges, such as 1-4, 8-15.
  • Set internally stores CPU numbers as bits in a bytestream, such as (hex) ff1e.

List.Set converts a List into its corresponding Set. In the opposite direction, Set.List converts a Set into its equivalent List.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetAffinity added in v0.6.0

func SetAffinity(tid int, cpus Set) error

SetAffinity sets the CPU affinities for the specified task/process, returning nil on success. Otherwise, it returns an error. It is an error trying to remove any CPU affinity by specifying an effectively empty Set.

See also the functional equivalent Set.PinTask.

Types

type List

type List [][2]uint

List is a list of CPU [from...to] ranges. CPU numbers are starting from zero.

The behavior of operations on Lists that are not in canonical form is undefined. In the canonical form of a List all its ranges are non-overlapping and in each range the first “from” element must be less or equal to the second “to” element.

func NewList

func NewList(text []byte) (List, error)

NewList returns a new CPU List for the given text. If the text is malformed then an error is returned instead.

The list textual format is a sequence of zero or more CPU ranges or single CPU numbers, separated by comma. A CPU range is in the form “from-to”, where “from” and “to” are non-negative CPU numbers separated by a minus sign as the poor-ASCII-people's dash surrogate.

Any trailing “\n” (or similar) is also an error.

Valid CPU lists:

  • “” (empty CPU list)
  • “42”
  • “1,2,42-666”

Invalid CPU lists (non-exhaustive examples):

  • “666,” (invalid trailing comma)
  • “666,,42” (invalid repeated comma)
  • “42-” (missing range end)
  • “42,foobar” (garbage)

func Online added in v0.10.0

func Online() List

Online returns the List of logical CPUs that are currently online. In case of any errors when the online CPUs cannot be determined, it returns an empty CPU list; but it never returns a nil List.

For background information, see also How CPU topology info is exported via sysfs in the Linux kernel documentation.

func (List) Contains added in v0.11.0

func (l List) Contains(cpu uint) bool

Contains reports whether cpu is in this CPU list.

func (List) Count added in v0.11.0

func (l List) Count() uint

Count returns the number of CPUs in this list.

func (List) Equal added in v0.11.0

func (l List) Equal(another List) bool

Equal returns true if both CPU lists are either nil or empty, or contain the same CPUs. The lists must be in canonical form.

func (List) IsOverlapping added in v0.7.0

func (l List) IsOverlapping(another List) bool

IsOverlapping returns true if this List overlaps with another List.

Both lists must be in canonical form where all ranges are ordered from lowest to highest and never overlap within the same list.

func (List) Overlap added in v0.6.0

func (l List) Overlap(another List) List

Overlap returns the overlap of this List with another List as a new List. If the range lists are not overlapping, then an empty new List is returned.

func (List) Remove added in v0.6.0

func (l List) Remove() (cpu uint, remaining List)

Remove the lowest CPU from the specified List, returning the CPU number together with a new List of remaining CPUs.

The Remove operation is useful to pick individual and available (“online”) CPUs after first getting the List of CPU affinities for a task/process.

Example

Pick two CPUs from the CPUs available to this process/task.

availset, err := Affinity(0)
if err != nil {
	panic(err)
}
acpu, avail := availset.List().Remove()
anothercpu, _ := avail.Remove()
println(acpu, anothercpu)

func (List) Set added in v0.6.0

func (l List) Set() Set

Set returns the CPU Set corresponding with this list.

func (List) String

func (l List) String() string

String returns the CPU list in textual format, with the individual ranges “x-y” separated by “,” and single CPU ranges collapsed into single CPU numbers “x” instead of an “x-x” range.

type Set

type Set []uint64

Set is a CPU bit string, such as used for CPU affinity masks. The first element represents the CPU numbers 0–63, with bit 0 (LSB) for CPU 0, bit 63 (MSB) for CPU 63. If present, the second element represents CPU numbers 64–127, with bit 0 (LSB) corresponding with CPU 64 and bit 63 (MSB) corresponding with CPU 127, and so on. A zero length Set represents an empty Set, as do non-zero length Sets with only zero value elements.

See also sched_getaffinity(2).

func Affinity

func Affinity(tid int) (Set, error)

Affinity returns the affinity CPUList (list of CPU ranges) of the process with the passed PID. Otherwise, it returns an error. If pid is zero, then the affinity CPU list of the calling thread is returned (make sure to have the OS-level thread locked to the calling go routine in this case).

Notes:

  • we don't use unix.SchedGetaffinity as this is tied to the fixed size unix.CPUSet type; instead, we dynamically figure out the size needed and cache the size internally.
  • retrieving the affinity CPU mask and then speed-running it to generate the range list is roughly two orders of magnitude faster than fetching “/proc/$PID/status” and looking for the “Cpus_allowed_list”, because generating the broad status procfs file is expensive.

func (Set) AddRange added in v0.7.0

func (s Set) AddRange(from, to uint) Set

AddRange adds the CPU(s) from the specified range, returning a new Set.

func (Set) IsOverlapping added in v0.7.0

func (s Set) IsOverlapping(another Set) bool

IsOverlapping returns true if this Set and another overlap, otherwise false.

func (Set) IsSet

func (s Set) IsSet(cpu uint) bool

IsSet reports whether cpu is in this CPU set.

func (Set) List

func (s Set) List() List

List returns the list of CPU ranges corresponding with this CPU Set.

This is an optimized implementation that does not use any division and modulo operations; instead, it only uses increment and (single bit position) shift operations. Additionally, this implementation fast-forwards through all-0s and all-1s CPUSet words (uint64's) wherever possible.

func (Set) Overlap added in v0.7.0

func (s Set) Overlap(another Set) Set

Overlap returns the overlap of this Set with another as a new Set.

func (Set) PinTask added in v0.7.0

func (s Set) PinTask(tid int) error

PinTask pins the process/task identified by tid to the CPUs specified in this Set. If it fails, it returns an error instead. PinTask is a convenience wrapper around calling SetAffinity with the specified Set.

func (Set) Single added in v0.8.0

func (s Set) Single() (cpu uint, ok bool)

Single returns the single CPU in a Set, or otherwise false if the Set is either empty or specifies multiple CPUs.

func (Set) String

func (s Set) String() string

String returns the CPUs in this set in textual list format. In list format, individual CPU ranges “x-y” are separated by “,”, and single CPU ranges collapsed into “x” (instead of “x-x”).

func (Set) SystemdDbusBytes added in v0.9.0

func (s Set) SystemdDbusBytes() []byte

SystemDbusBytes returns the set as a slice of bytes in little-endian format as required by systemd's D-Bus API.

Please note that the byte slice is always in little-endian format with CPUs 0-7 in the first byte, 8-15 in the second byte, and so on, regardless of the host endianess.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL