Buffered channels in Go
A buffer lets a sender run ahead, up to its capacity.
func buffered() (int, int, []int) {
queue := make(chan int, 3)
queue <- 1
queue <- 2
queued, capacity := len(queue), cap(queue)
close(queue)
var drained []int
for value := range queue { // range stops at close
drained = append(drained, value)
}
return queued, capacity, drained
}
How it works
make(chan T, n)holds n values before blocking.lenis what is queued,capis the buffer size.- A full buffer blocks the sender; an empty one blocks the receiver.
Keywords and builtins used here
appendcapchancloseforfuncintlenmakerangereturnvar
The run, in numbers
- Lines
- 14
- Characters to type
- 281
- Tokens
- 74
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 44 seconds.
Step 2 of 4 in Channels, step 5 of 25 in Concurrency.