parallel.go 803 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*Package parallel provides helper functions for the dispatching of parallel jobs.*/
  2. package parallel
  3. import (
  4. "runtime"
  5. "sync"
  6. )
  7. func init() {
  8. runtime.GOMAXPROCS(runtime.NumCPU())
  9. }
  10. // Line dispatches a parameter fn into multiple goroutines by splitting the parameter length
  11. // by the number of available CPUs and assigning the length parts into each fn.
  12. func Line(length int, fn func(start, end int)) {
  13. procs := runtime.GOMAXPROCS(0)
  14. counter := length
  15. partSize := length / procs
  16. if procs <= 1 || partSize <= procs {
  17. fn(0, length)
  18. } else {
  19. var wg sync.WaitGroup
  20. for counter > 0 {
  21. start := counter - partSize
  22. end := counter
  23. if start < 0 {
  24. start = 0
  25. }
  26. counter -= partSize
  27. wg.Add(1)
  28. go func() {
  29. defer wg.Done()
  30. fn(start, end)
  31. }()
  32. }
  33. wg.Wait()
  34. }
  35. }