Junior — Middle
Is it allowed to send messages to the same channel by multiple goroutines simultaneously?
sobes.tech AI
Answer from AI
Yes, in Go it is allowed to send messages to a single channel from multiple goroutines simultaneously. Channels in Go are thread-safe and provide synchronization between goroutines.
However, it is important to remember:
- If multiple goroutines write to a single channel and no one reads from it, this will lead to blocking.
- If the channel is buffered, writes will only block when the buffer is full.
- Proper management of channel closing is crucial — only the sender should close the channel, and only when it is sure that no more data will be sent.
Example:
ch := make(chan int)
// Launching multiple goroutines sending data to the channel
for i := 0; i < 3; i++ {
go func(id int) {
ch <- id
}(i)
}
// Reading from the channel
for i := 0; i < 3; i++ {
fmt.Println(<-ch)
}
Thus, concurrent sending to a channel from multiple goroutines is standard practice in Go.