Do buffered channels maintain order?

lanrat picture lanrat · Sep 11, 2014 · Viewed 7.8k times · Source

In Go, do buffered channels have any order guarantee?

For example: you have two goroutines A & B that share a channel. A pushes data onto the channel while B reads from it. Are you guranted that B will read data In the same order that A put it into the channel?

I understand that if there are multiple producers or consumers the order may be non-deterministic, but I'm specifically asking about having just 1 producer and 1 consumer.

Answer

VonC picture VonC · Sep 11, 2014

"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.