Junior — Middle
How is interaction via a buffered channel implemented and how is data transferred?
sobes.tech AI
Answer from AI
In Go, a buffered channel is created by specifying the buffer size, for example: ch := make(chan int, 3). Such a channel can hold up to 3 elements without blocking the sender.
When transmitting data through a buffered channel:
- The sender (
chan <- value) places the value into the channel buffer. If the buffer is not full, the operation does not block. - If the buffer is full, the sender blocks until there is space available.
- The receiver (
value := <- chan) retrieves a value from the buffer. If the buffer is empty, the receiver blocks until data becomes available.
Example:
ch := make(chan int, 2)
ch <- 1 // does not block, buffer now has 1 element
ch <- 2 // does not block, buffer now has 2 elements (full buffer)
fmt.Println(<-ch) // outputs 1, freeing space in the buffer
ch <- 3 // now it can send, as there is space
Thus, buffered channels allow temporary storage of data and reduce blocking between goroutines.