Junior — Middle
How does the mechanism of writing to a restricted access channel work and what happens during this process?
sobes.tech AI
Answer from AI
In Go, a buffered channel with limited capacity has a fixed buffer size. When data is written to the channel using the operation chan <- value, the following occurs:
- If there is free space in the buffer, the value is placed in the buffer, and the write operation completes immediately.
- If the buffer is full, the write operation blocks until someone reads a value from the channel, freeing up space.
Thus, a buffered channel provides synchronization between goroutines: writing blocks when the buffer is full, and reading blocks when the buffer is empty.
Example:
ch := make(chan int, 2) // buffer of 2 elements
ch <- 1 // write, buffer: [1]
ch <- 2 // write, buffer: [1, 2]
// ch <- 3 // blocks because the buffer is full
fmt.Println(<-ch) // reads 1, buffer: [2]
ch <- 3 // now the write will succeed
Therefore, the mechanism of writing to a limited access channel ensures control over data flow and prevents buffer overflow.