Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe way to funnel data from multiple go routines

Tags:

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.

like image 465
Chris Avatar asked Dec 03 '12 20:12

Chris


1 Answers

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.

like image 85
Daniel Avatar answered Sep 30 '22 02:09

Daniel