6,356 viewsAsked at 27 companies
What are unbuffered channels used for? Why can't a channel with a large buffer always be used?
Asked at
AI answer
A buffered channel with length 1 in Go allows the sender to write one value into the channel without blocking if the buffer is empty. The receiver can read this value later. This provides a small degree of asynchrony between sender and receiver.
An unbuffered channel with length 0 (the default) requires the sender and receiver to be ready at the same time for the transfer — sending blocks until someone reads the value, and vice versa.
Example:
ch := make(chan int, 1) // buffered channel with length 1
ch <- 42 // does not block if the buffer is empty
ch2 := make(chan int) // unbuffered channel
// ch2 <- 42 // blocks until someone reads
Thus, a buffered channel with length 1 slightly relieves synchronization between goroutines, while an unbuffered channel requires strict data transfer synchronization.
Also asked at Wildberries
Similar questions
- Tell me about buffered and unbuffered channels. When do we use which? How do they block, and when do they lead to deadlock?
- How should data be correctly read from a non-buffered channel?
- Is it possible to write data to a channel simultaneously without using a buffer?
- Which channel transmits data faster: buffered or unbuffered?
- What happens if you write data to a non-buffered channel without checking its state or reading from it?