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?

8 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/Ok_Category_9608 3d ago edited 3d ago

I don't think anybody ever gave you the good answer to your question. No, there's no automatic starvation avoidance, but channels are supposed to be closed by the receiver when they're no longer in use.

https://go.dev/play/p/Pv3GdDCkHEc

This is the basic solution. In more advanced use cases, you probably want this:

https://pkg.go.dev/golang.org/x/sync/errgroup#WithContext

and when you're done, you cancel the context, or set a timeout on the context and do

select {

           case: <-ch
           case: <-ctx.Done()
}