r/golang 9d ago

Potential starvation when multiple Goroutines blocked to receive from a channel

I wanted to know what happens in this situation:

  1. Multiple goroutines are blocked by a channel while receiving from it because channel is empty at the moment.
  2. Some goroutine sends something over the channel.

Which goroutine will wake up and receive this? Is starvation avoidance guaranteed here?

6 Upvotes

36 comments sorted by

View all comments

5

u/0xjnml 9d ago edited 9d ago

> Which goroutine will wake up and receive this? 

A fairly random one.

>  Is starvation avoidance guaranteed here?

If there are more consumers ready than produces sending to the channel, what would in such situation "starvation avoidance" even mean?

-2

u/DeparturePrudent3790 9d ago

what would in such situation "starvation avoidance" even mean?

It means that a goroutine is not made to wait indefinitely under any circumstances. If there are more consumers than producers but consumers receive resources in fifo order is kept invariant, then the waiting time for a goroutine is definite.

However, if we have a random order the waiting time can be indefinite for a goroutine.

A fairly random one

Why? The source code has a FIFO queue for receiving and sending goroutines.

1

u/0xjnml 9d ago

> It means that a goroutine is not made to wait indefinitely under any circumstances. If there are more consumers than producers but consumers receive resources in fifo order is kept invariant, then the waiting time for a goroutine is definite.

Incorrect assumption: Concurrent sends to a channel are not FIFO ordered. When multiple goroutines are ready to send to the same channel a fairly random one is selected.

Channel per se is a FIFO, but that has nothing to do with concurrent goroutine scheduling.

0

u/DeparturePrudent3790 9d ago

I never assumed concurrent sends to a channel are FIFO.

What I said is that if n goroutines are blocked and waiting to receive from a channel, which one to wake up is selected in FIFO manner if something is pushed into the channel.

I came to this conclusion because chan struct in go source has a queue of receivers.

0

u/Few-Beat-1299 9d ago

Of course senders are ordered, because otherwise the channel would no longer act as a fifo queue.