Junior — Middle
Kuidas töötab piiratud juurdepääsuga kanali salvestusmehhanism ja mis selle protsessi käigus toimub?
sobes.tech AI
Vastus AI-lt
In the Go language, a channel with limited capacity (buffered channel) has a fixed buffer size. When writing data to the channel using the operation chan <- value, the following occurs:
- If there is free space in the channel's buffer, the value is placed into 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.
This way, a limited capacity channel provides synchronization between goroutines: writing blocks on overflow, and reading blocks on an empty buffer.
Example:
ch := make(chan int, 2) // buffer for 2 elements
ch <- 1 // write, buffer: [1]
ch <- 2 // write, buffer: [1, 2]
// ch <- 3 // blocks, because buffer is full
fmt.Println(<-ch) // read 1, buffer: [2]
ch <- 3 // now the write will succeed
This mechanism of writing to a limited access channel ensures control over data flow and prevents buffer overflow.