Buffered channels
- Version
- 1.27
- Review
- Draft
Summary#
A buffered channel accepts sends without a waiting receiver until its buffer is full. An unbuffered channel needs a sender and a receiver to be ready together. When one goroutine sends a sequence of values and another receives them, the receiver sees them in the same order.
Syntax#
queue := make(chan string, 2)
waiting, capacity := len(queue), cap(queue)
Example#
package main
import "fmt"
func offer(queue chan<- string, job string) {
select {
case queue <- job:
fmt.Println("accepted", job)
default:
fmt.Println("no room for", job)
}
}
func main() {
queue := make(chan string, 2)
offer(queue, "resize")
offer(queue, "upload")
offer(queue, "notify")
fmt.Println(len(queue), cap(queue))
fmt.Println("took", <-queue) // frees one slot
offer(queue, "notify")
fmt.Println(<-queue, <-queue)
direct := make(chan string) // capacity 0
offer(direct, "ping")
}
Expected output#
accepted resize
accepted upload
no room for notify
2 2
took resize
accepted notify
upload notify
no room for ping
Common mistakes#
A buffer only delays blocking. A send to a full open channel waits for space. Do not check len and then send when other goroutines use the channel, because the state can change in between. Use select with default for a non-blocking send. Sending to a closed channel still panics, even inside that select.
Version applicability#
These buffering rules apply to Go 1.27 and earlier Go versions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0