Browse code

Use functions from x/sys/unix to get number of CPUs on Linux

Use Getpid and SchedGetaffinity from golang.org/x/sys/unix to get the
number of CPUs in numCPU on Linux.

Signed-off-by: Tobias Klauser <tklauser@distanz.ch>

Tobias Klauser authored on 2019/06/19 02:26:56
Showing 3 changed files
... ...
@@ -2,7 +2,6 @@ package sysinfo // import "github.com/docker/docker/pkg/sysinfo"
2 2
 
3 3
 import (
4 4
 	"runtime"
5
-	"unsafe"
6 5
 
7 6
 	"golang.org/x/sys/unix"
8 7
 )
... ...
@@ -14,23 +13,15 @@ import (
14 14
 // Returns 0 on errors. Use |runtime.NumCPU| in that case.
15 15
 func numCPU() int {
16 16
 	// Gets the affinity mask for a process: The very one invoking this function.
17
-	pid, _, _ := unix.RawSyscall(unix.SYS_GETPID, 0, 0, 0)
17
+	pid := unix.Getpid()
18 18
 
19
-	var mask [1024 / 64]uintptr
20
-	_, _, err := unix.RawSyscall(unix.SYS_SCHED_GETAFFINITY, pid, uintptr(len(mask)*8), uintptr(unsafe.Pointer(&mask[0])))
21
-	if err != 0 {
19
+	var mask unix.CPUSet
20
+	err := unix.SchedGetaffinity(pid, &mask)
21
+	if err != nil {
22 22
 		return 0
23 23
 	}
24 24
 
25
-	// For every available thread a bit is set in the mask.
26
-	ncpu := 0
27
-	for _, e := range mask {
28
-		if e == 0 {
29
-			continue
30
-		}
31
-		ncpu += int(popcnt(uint64(e)))
32
-	}
33
-	return ncpu
25
+	return mask.Count()
34 26
 }
35 27
 
36 28
 // NumCPU returns the number of CPUs which are currently online
... ...
@@ -13,6 +13,16 @@ var (
13 13
 	getProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
14 14
 )
15 15
 
16
+// Returns bit count of 1, used by NumCPU
17
+func popcnt(x uint64) (n byte) {
18
+	x -= (x >> 1) & 0x5555555555555555
19
+	x = (x>>2)&0x3333333333333333 + x&0x3333333333333333
20
+	x += x >> 4
21
+	x &= 0x0f0f0f0f0f0f0f0f
22
+	x *= 0x0101010101010101
23
+	return byte(x >> 56)
24
+}
25
+
16 26
 func numCPU() int {
17 27
 	// Gets the affinity mask for a process
18 28
 	var mask, sysmask uintptr
... ...
@@ -146,13 +146,3 @@ func isCpusetListAvailable(provided, available string) (bool, error) {
146 146
 	}
147 147
 	return true, nil
148 148
 }
149
-
150
-// Returns bit count of 1, used by NumCPU
151
-func popcnt(x uint64) (n byte) {
152
-	x -= (x >> 1) & 0x5555555555555555
153
-	x = (x>>2)&0x3333333333333333 + x&0x3333333333333333
154
-	x += x >> 4
155
-	x &= 0x0f0f0f0f0f0f0f0f
156
-	x *= 0x0101010101010101
157
-	return byte(x >> 56)
158
-}