Vipul Kumar
Vipul Kumar

Reputation: 269

Data duplication by multiple goroutines

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?

Upvotes: 0

Views: 884

Answers (2)

Richard Chambers
Richard Chambers

Reputation: 17573

Channels are one of the primary ways for goroutines to synchronize with each other. Therefore 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 the 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?

You can depend on 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 Go.

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.

Upvotes: 2

Spi1y
Spi1y

Reputation: 92

There is a quite good analysis of Go channel internals here https://codeburst.io/diving-deep-into-the-golang-channels-549fd4ed21a8
Basically, the channel maintains an internal queue of goroutines waiting for the read operations. And when something is sent, it just selects one goroutine from that queue and feeds it with data. If there is no one waiting - data goes into a buffer or blocks the writer.

Upvotes: 0

Related Questions