Do buffered channels maintain order?

“Are you guaranteed that B will read data In the same order that A put it into the channel?”

Yes. The order of data is guaranteed.
But the delivery is guaranteed only for unbuffered channels, not buffered.
(see second section of this answer)


You can see the idea of channels illustrated in “The Nature Of Channels In Go” from William Kennedy (Feb. 2014): it shows how the order or read/write is respected.
See also Channels:

Receivers always block until there is data to receive.

  • If the channel is unbuffered, the sender blocks until the receiver has received the value.
  • If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.

Unbuffered Channels

https://www.ardanlabs.com/images/goinggo/Screen+Shot+2014-02-16+at+10.10.54+AM.png

Buffered Channel

https://www.ardanlabs.com/images/goinggo/Screen+Shot+2014-02-17+at+8.38.15+AM.png

Image source: Ardan labs – William Kennedy


The same William Kennedy details the Guarantee Of Delivery aspect in “The Behavior Of Channels” (Oct 2017)

Do I need a guarantee that the signal sent by a particular goroutine has been received?

https://www.ardanlabs.com/images/goinggo/86_signaling_with_data.png

Image source: Again, Ardan labs – William Kennedy

The three channel options are Unbuffered, Buffered >1 or Buffered =1.

  • Guarantee

    • An Unbuffered channel gives you a Guarantee that a signal being sent has been received.
      • Because the Receive of the signal Happens Before the Send of the signal completes.
  • No Guarantee

    • A Buffered channel of size >1 gives you No Guarantee that a signal being sent has been received.
      • Because the Send of the signal Happens Before the Receive of the signal completes.
  • Delayed Guarantee

    • A Buffered channel of size =1 gives you a Delayed Guarantee. It can guarantee that the previous signal that was sent has been received.
      • Because the Receive of the First Signal, Happens Before the Send of the Second Signal completes.

Leave a Comment