Path: blob/main/vendor/golang.org/x/sys/unix/affinity_linux.go
2880 views
// Copyright 2018 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34// CPU affinity functions56package unix78import (9"math/bits"10"unsafe"11)1213const cpuSetSize = _CPU_SETSIZE / _NCPUBITS1415// CPUSet represents a CPU affinity mask.16type CPUSet [cpuSetSize]cpuMask1718func schedAffinity(trap uintptr, pid int, set *CPUSet) error {19_, _, e := RawSyscall(trap, uintptr(pid), uintptr(unsafe.Sizeof(*set)), uintptr(unsafe.Pointer(set)))20if e != 0 {21return errnoErr(e)22}23return nil24}2526// SchedGetaffinity gets the CPU affinity mask of the thread specified by pid.27// If pid is 0 the calling thread is used.28func SchedGetaffinity(pid int, set *CPUSet) error {29return schedAffinity(SYS_SCHED_GETAFFINITY, pid, set)30}3132// SchedSetaffinity sets the CPU affinity mask of the thread specified by pid.33// If pid is 0 the calling thread is used.34func SchedSetaffinity(pid int, set *CPUSet) error {35return schedAffinity(SYS_SCHED_SETAFFINITY, pid, set)36}3738// Zero clears the set s, so that it contains no CPUs.39func (s *CPUSet) Zero() {40clear(s[:])41}4243// Fill adds all possible CPU bits to the set s. On Linux, [SchedSetaffinity]44// will silently ignore any invalid CPU bits in [CPUSet] so this is an45// efficient way of resetting the CPU affinity of a process.46func (s *CPUSet) Fill() {47for i := range s {48s[i] = ^cpuMask(0)49}50}5152func cpuBitsIndex(cpu int) int {53return cpu / _NCPUBITS54}5556func cpuBitsMask(cpu int) cpuMask {57return cpuMask(1 << (uint(cpu) % _NCPUBITS))58}5960// Set adds cpu to the set s.61func (s *CPUSet) Set(cpu int) {62i := cpuBitsIndex(cpu)63if i < len(s) {64s[i] |= cpuBitsMask(cpu)65}66}6768// Clear removes cpu from the set s.69func (s *CPUSet) Clear(cpu int) {70i := cpuBitsIndex(cpu)71if i < len(s) {72s[i] &^= cpuBitsMask(cpu)73}74}7576// IsSet reports whether cpu is in the set s.77func (s *CPUSet) IsSet(cpu int) bool {78i := cpuBitsIndex(cpu)79if i < len(s) {80return s[i]&cpuBitsMask(cpu) != 081}82return false83}8485// Count returns the number of CPUs in the set s.86func (s *CPUSet) Count() int {87c := 088for _, b := range s {89c += bits.OnesCount64(uint64(b))90}91return c92}939495