Quantcast
Channel: User Schwern - Stack Overflow
Viewing all articles
Browse latest Browse all 581

Answer by Schwern for Access from multiple goroutines to a single array

$
0
0

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()}

Demonstration.

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.

Demonstration


Viewing all articles
Browse latest Browse all 581

Trending Articles