Junior — Middle
What is the difference between a buffered channel and an unbuffered channel in the context of inter-goroutine communication?
sobes.tech AI
Answer from AI
An unbuffered channel blocks the sender until the receiver reads the value, and vice versa — the receiver blocks until a value appears. This ensures synchronization between goroutines.
A buffered channel has an internal buffer of fixed size. The sender can send multiple values in a row without blocking until the buffer is full. The receiver can read values from the buffer without waiting for the sender, if the buffer is not empty.
Example:
ch := make(chan int) // unbuffered
chBuf := make(chan int, 2) // buffered with 2 elements
// ch <- 1 // will block if there is no receiver
chBuf <- 1 // will not block until the buffer is full
Thus, buffered channels allow more flexible synchronization management and can improve performance by reducing the number of blocking operations.