threads.go 689 B

123456789101112131415161718192021222324252627282930313233343536
  1. package cpu
  2. import (
  3. "math"
  4. "runtime"
  5. )
  6. var maxThreads int
  7. // init defaults to 90% of available cores (at least 1).
  8. func init() {
  9. SetMaxThreads(-1)
  10. }
  11. // SetMaxThreads updates the maximum CPU worker count used by CPU kernels.
  12. // Passing n <= 0 picks 90% of available cores. Clamped to [1, NumCPU].
  13. // It also sets GOMAXPROCS to match to avoid oversubscription.
  14. func SetMaxThreads(n int) {
  15. cores := runtime.NumCPU()
  16. if cores < 1 {
  17. cores = 1
  18. }
  19. if n <= 0 || n > cores {
  20. n = int(math.Ceil(0.9 * float64(cores)))
  21. if n < 1 {
  22. n = 1
  23. }
  24. }
  25. maxThreads = n
  26. runtime.GOMAXPROCS(n)
  27. }
  28. // MaxThreads returns the configured worker count.
  29. func MaxThreads() int {
  30. return maxThreads
  31. }