Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

go - 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?

question from:https://stackoverflow.com/questions/65832949/data-duplication-by-multiple-goroutines

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...