Yes, you can do that. Here's one way, rather than passing in fixed ranges the workers do their own iteration. Note the use of sync.WaitGroup to ensure main waits for all workers to complete.
package mainimport ("fmt""sync")func main() { const num_workers = 3 var numbers = []int{1, 3, 5, 9, 12, 14, 15, 16, 17, 20, 22, 100, 101, 103, 99, 55, 1039, 938} var wg sync.WaitGroup for i := 0; i < num_workers; i++ { wg.Add(1) go func() { defer wg.Done() for j := i; j < len(numbers); j += num_workers { fmt.Printf("worker: %d, input: %d\n", i, numbers[j]) } }() } wg.Wait()}
But the more idiomatic way in Go is to use a channel. Workers pull the numbers from the channel as needed.
package mainimport ("fmt""sync")func main() { const num_workers = 3 var numbers = []int{1, 3, 5, 9, 12, 14, 15, 16, 17, 20, 22, 100, 101, 103, 99, 55, 1039, 938} inputs := make(chan int) var wg sync.WaitGroup for i := 0; i < num_workers; i++ { wg.Add(1) go func() { defer wg.Done() for input := range inputs { fmt.Printf("worker: %d, input: %d\n", i, input) } }() } // main feeds the numbers into the channel. for _, num := range numbers { inputs <- num } // this allows `for input := range inputs` to exit // once the channel is empty close(inputs) wg.Wait()}
This supports a changing number of workers, and workers can go at their own pace. The numbers do not need to be slurped into memory, the channel can be fed from a stream.