Junior — Middle
How to implement safe reading of data from a channel in multiple goroutines simultaneously?
sobes.tech AI
Answer from AI
In Go, to safely read from a channel by multiple goroutines simultaneously, the following approaches are usually used:
-
One sender, multiple receivers — a channel is created, and multiple goroutines read from it. In Go, channels are safe for concurrent reading from multiple goroutines, so you can simply launch multiple goroutines that read from a single channel.
-
Using
sync.WaitGroupfor synchronization — to wait for all goroutines to finish.
Example:
package main
import (
"fmt"
"sync"
)
func worker(id int, ch <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
for val := range ch {
fmt.Printf("Worker %d received %d\n", id, val)
}
}
func main() {
ch := make(chan int)
var wg sync.WaitGroup
// Launch 3 goroutines that read from the channel
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(i, ch, &wg)
}
// Send data into the channel
for i := 0; i < 10; i++ {
ch <- i
}
close(ch) // Close the channel to signal goroutines to finish
wg.Wait() // Wait for all goroutines to finish
}
Thus, the channel in Go already provides safe access when reading from multiple goroutines; the main thing is to properly manage their lifecycle and close the channel.