I'm learning about goroutines and channels and have a question about what happens if multiple goroutines try fetching data from the same channel.
How does the go runtime makes sure that data in a channel that is being read by multiple goroutines is provided to only one of the goroutines waiting on the channel and not duplicated or sent to multiple goroutines.
Does the go runtime prevent race conditions when there are multiple goroutines trying to fetch data from the exact same channel? Is there some kind of ordering as to which of the waiting goroutines is given the data for instance First Come First Served?
Channels are one of the primary ways for goroutines to synchronize with each other therefor they contain a mechanism to ensure that only one goroutine at a time is able to pull a data item from a channel and that the data item retrieved is not duplicated.
You can't really count on any particular sequence of multiple goroutines reading successfully from the same channel as which specific goroutine's read will complete depends on multi-threading algorithm used.
See this discussion, Goroutines are cooperatively scheduled. Does that mean that goroutines that don't yield execution will cause goroutines to run one by one?
What you can depend on is that if multiple goroutines are reading from the same channel then when there is data in the channel to be read, one of those goroutines will succeed in its read and the data read will not be read by any of the other goroutines that are waiting on a read from the channel to succeed.
See Concurrency from golang-book.com which explains concurrency and goroutines and channels.
See as well How to use channels to safely synchronise data in Golang
See as well this answer which describes using channels rather than a synchronization primitive such as a mutex to maintain a dynamic list of listeners https://stackoverflow.com/a/18897083/1466970
See also this long and somewhat exhausting description of Anatomy of Channels in Go - Concurrency in Go.
2.1m questions
2.1m answers
60 comments
57.0k users