9 var CPU_PATH = "/sys/fs/cgroup/cpuset.cpus.effective"
11 type CpuContext struct {
12 cpuAllocator *CpuAllocatorT
16 func (c *CpuContext) Release() {
17 c.cpuAllocator.cpus = append(c.cpuAllocator.cpus, c.cpus...)
18 c.cpus = c.cpus[:0] // empty the list
21 type CpuAllocatorT struct {
25 var cpuAllocator *CpuAllocatorT = nil
27 func (c *CpuAllocatorT) Allocate(nCpus int) (*CpuContext, error) {
30 if len(c.cpus) < nCpus {
31 return nil, fmt.Errorf("could not allocate %d CPUs; available: %d", nCpus, len(c.cpus))
33 cpuCtx.cpus = c.cpus[0:nCpus]
34 cpuCtx.cpuAllocator = c
35 c.cpus = c.cpus[nCpus:]
39 func (c *CpuAllocatorT) readCpus(fname string) error {
41 file, err := os.Open(CPU_PATH)
47 sc := bufio.NewScanner(file)
50 _, err = fmt.Sscanf(line, "%d-%d", &first, &last)
54 for i := first; i <= last; i++ {
55 c.cpus = append(c.cpus, i)
60 func CpuAllocator() (*CpuAllocatorT, error) {
61 if cpuAllocator == nil {
62 cpuAllocator = new(CpuAllocatorT)
63 err := cpuAllocator.readCpus(CPU_PATH)
68 return cpuAllocator, nil