Middle+
What is the difference between buffered and unbuffered channels?
sobes.tech AI
Answer from AI
Buffered channels in Go have an internal buffer of fixed size, which allows the sender to write multiple values into the channel without waiting for immediate receipt. This means that sending to the channel does not block until the buffer is full.
Unbuffered channels do not have an internal buffer, so the send operation blocks until another goroutine reads a value from the channel. Similarly, the read operation blocks if there is no value in the channel.
Example:
ch := make(chan int, 2) // buffered channel with a buffer of 2 elements
ch <- 1 // does not block
ch <- 2 // does not block
// ch <- 3 // blocks until someone reads
ch2 := make(chan int) // unbuffered channel
// ch2 <- 1 // blocks until someone reads
Thus, buffered channels allow more flexible management of synchronization between goroutines, reducing blocking, while unbuffered channels provide strict synchronization between sender and receiver.