Kenenbek Arzymatov
Kenenbek Arzymatov

Reputation: 9139

Communication in Go via channels

Consider such situation. There are one main goroutine and ten subsidiary goroutines. All of them have access to channel. Main one sends 1000 numbers to this channel and subsidiary ones will read from it. Is there any guarantee that each subsidiary goroutine will read exactly 100 numbers or this amount may vary like some goroutine will read 99 numbers and another 101?

Upvotes: 0

Views: 73

Answers (2)

Sudhir Jonathan
Sudhir Jonathan

Reputation: 17526

With goroutine scheduling via an unbuffered channel, then interesting thing to note is that the channel serves purely as a blocking mechanism - in that the value is never "sent into the channel" and nothing actually "reads from" it.

An unbuffered channel works purely as a synchronization mechanism: for the goroutine sending on a channel, it works more along the lines of "sleep until some goroutine is ready to receive" and for the receiving goroutine it's "sleep until some goroutine is ready to send".

This should make it clear that sends and receives have no kind of fairness or distribution system built in - they're purely first come first served, or possibly even more arbitrary depending on the scheduler's current load.

Upvotes: 1

user8981190
user8981190

Reputation:

No, there is no guarantee, because it depends on the runtime of every goroutine and that depends on how well the goroutines are distributed across the CPU.

Upvotes: 2

Related Questions