Given the following example: http://play.golang.org/p/owvJ8Oi77S
func produce(dataChannel chan int) { for i := 0; i < 10; i++ { dataChannel <- i } } func main() { dataChannel := make(chan int) go produce(dataChannel) go produce(dataChannel) go produce(dataChannel) for i := 0; i < 30; i++ { data := <-dataChannel fmt.Printf("%v ", data) } }
Is my assumption that writing to a channel from multiple go routines unsafe correct?
Is there a common/idiomatic way to do this safely? I know you can make a separate channel for each routine that's producing data, I was just wondering if that was the cleanest solution or if there are other alternatives.
Channels are completely thread safe. They are the official way to communicate between goroutines. I see nothing wrong with your code. This is the beauty of Go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With