numcpu_linux.go 926 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package sysinfo
  2. import (
  3. "runtime"
  4. "unsafe"
  5. "golang.org/x/sys/unix"
  6. )
  7. // numCPU queries the system for the count of threads available
  8. // for use to this process.
  9. //
  10. // Issues two syscalls.
  11. // Returns 0 on errors. Use |runtime.NumCPU| in that case.
  12. func numCPU() int {
  13. // Gets the affinity mask for a process: The very one invoking this function.
  14. pid, _, _ := unix.RawSyscall(unix.SYS_GETPID, 0, 0, 0)
  15. var mask [1024 / 64]uintptr
  16. _, _, err := unix.RawSyscall(unix.SYS_SCHED_GETAFFINITY, pid, uintptr(len(mask)*8), uintptr(unsafe.Pointer(&mask[0])))
  17. if err != 0 {
  18. return 0
  19. }
  20. // For every available thread a bit is set in the mask.
  21. ncpu := 0
  22. for _, e := range mask {
  23. if e == 0 {
  24. continue
  25. }
  26. ncpu += int(popcnt(uint64(e)))
  27. }
  28. return ncpu
  29. }
  30. // NumCPU returns the number of CPUs which are currently online
  31. func NumCPU() int {
  32. if ncpu := numCPU(); ncpu > 0 {
  33. return ncpu
  34. }
  35. return runtime.NumCPU()
  36. }