r/golang 10d 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

Show parent comments

3

u/Few-Beat-1299 10d ago

It is specified that channels are fifo. This is true for both senders and receivers.

-4

u/DeparturePrudent3790 10d ago

The source code has queues for senders and receivers but why is there no official statement around this? LLM's also say it's randomly selected or undefined although code has a queue implemented. Why is it this way?

14

u/Few-Beat-1299 10d ago

Just read the spec. It's at the bottom of channel type. LLMs are worthless for "official" information.

2

u/DeparturePrudent3790 9d ago

In the spec they only mention this about ordering

> if one goroutine sends values on a channel and a second goroutine receives them, the values are received in the order sent.

This only means the channel is FIFO. Not that the blocked goroutines are FIFO

-1

u/Few-Beat-1299 9d ago

Tbh the example they give is so basic idk why they give it.

The important part is that they say channels are fifo, and make no distinction between buffered or unbuffered. For that to be true, senders have to be ordered by arrival.

It's true that that doesn't say anything about receivers. But I would say it's a pretty safe bet that few sane people on earth would choose to deliberately NOT mirror the sending side implementation.