numcpu_windows.go 868 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // +build windows
  2. package sysinfo
  3. import (
  4. "runtime"
  5. "unsafe"
  6. "golang.org/x/sys/windows"
  7. )
  8. var (
  9. kernel32 = windows.NewLazySystemDLL("kernel32.dll")
  10. getCurrentProcess = kernel32.NewProc("GetCurrentProcess")
  11. getProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
  12. )
  13. func numCPU() int {
  14. // Gets the affinity mask for a process
  15. var mask, sysmask uintptr
  16. currentProcess, _, _ := getCurrentProcess.Call()
  17. ret, _, _ := getProcessAffinityMask.Call(currentProcess, uintptr(unsafe.Pointer(&mask)), uintptr(unsafe.Pointer(&sysmask)))
  18. if ret == 0 {
  19. return 0
  20. }
  21. // For every available thread a bit is set in the mask.
  22. ncpu := int(popcnt(uint64(mask)))
  23. return ncpu
  24. }
  25. // NumCPU returns the number of CPUs which are currently online
  26. func NumCPU() int {
  27. if ncpu := numCPU(); ncpu > 0 {
  28. return ncpu
  29. }
  30. return runtime.NumCPU()
  31. }