Sobes.tech
Senior

What is the difference between buffered and unbuffered channels?

sobes.tech AI

Answer from AI

In Go, channels can be buffered or unbuffered, and the main difference between them is the presence of an internal buffer for storing messages.

  • Unbuffered channel (buffer size = 0):

    • Sending (chan <- value) blocks until another goroutine reads the value from the channel.
    • Receiving (<- chan) blocks if there is no value in the channel.
    • Used for synchronization and transferring data "on the fly", without intermediate storage.
  • Buffered channel (buffer size > 0):

    • Has an internal buffer of fixed size.
    • Sending blocks only if the buffer is full.
    • Receiving blocks if the buffer is empty.
    • Allows the sender to continue working until the buffer is filled, increasing asynchrony.

Example:

ch := make(chan int, 2) // buffer of 2 elements
ch <- 1 // does not block
ch <- 2 // does not block
// ch <- 3 // blocks until someone reads

val := <-ch // reading frees space in the buffer

The choice between them depends on synchronization and performance requirements. Unbuffered channels provide strict synchronization, while buffered channels allow more flexible data flow management.

What is the difference between buffered and… - sobes.tech