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