July 2019
Intermediate to advanced
458 pages
12h 12m
English
Having multiple producers or consumers can be easily handled using wait groups. In the case of multiple producers, all the goroutines will share the same channel:
// three producervar ch = make(chan string)wg := sync.WaitGroup{}wg.Add(3)for i := 0; i < 3; i++ { go func(n int) { for i := 0; i < 100; i++ { ch <- fmt.Sprintln(n, i) } wg.Done() }(i)}go func() { wg.Wait() close(ch)}()
The full example is available here: https://play.golang.org/p/4DqWKntl6sS.
They will use sync.WaitGroup to wait for each producer to finish before closing the channel.
Read now
Unlock full access