Go Buffered Channels
A buffered channel has room to store a fixed number of values. You create one by giving make a capacity:
ch := make(chan string, 3) // can hold up to 3 stringsThe difference from an unbuffered channel is all about when operations block:
Unbuffered make(chan T) |
Buffered make(chan T, n) |
|
|---|---|---|
| Send blocks when… | no receiver is ready | the buffer is full |
| Receive blocks when… | no sender is ready | the buffer is empty |
| Sender and receiver meet? | yes, every time (synchronous) | no, they are decoupled (asynchronous) |
Sending without a receiver
With room in the buffer, a single goroutine can send and later receive — something that would deadlock on an unbuffered channel.
package main
import "fmt"
func main() {
queue := make(chan string, 3)
queue <- "first" // does not block: buffer has space
queue <- "second"
fmt.Println("len:", len(queue), "cap:", cap(queue))
fmt.Println(<-queue) // FIFO: first in, first out
fmt.Println(<-queue)
fmt.Println("len now:", len(queue))
}len: 2 cap: 3
first
second
len now: 0
len(ch) reports how many values are waiting in the buffer and cap(ch) its capacity. They are handy for debugging, but don't base program logic on len — it can change the moment after you read it.
When the buffer is full
Sending to a full buffer blocks until someone receives. If nobody ever will, it is a deadlock:
package main
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
ch <- 3 // buffer full, no receiver: deadlock
}fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
./example.go:7 +0x56
Producer and consumer
Buffers let a fast producer run ahead of a slower consumer, smoothing out bursts. The values still arrive in exactly the order they were sent.
package main
import "fmt"
func main() {
jobs := make(chan int, 5)
done := make(chan []string)
// consumer
go func() {
var log []string
for j := range jobs {
log = append(log, fmt.Sprintf("processed job %d", j))
}
done <- log
}()
// producer: can queue up to 5 jobs without waiting
for i := 1; i <= 4; i++ {
jobs <- i
}
close(jobs)
for _, line := range <-done {
fmt.Println(line)
}
}processed job 1
processed job 2
processed job 3
processed job 4
A buffered channel as a semaphore
A channel with capacity n can limit how many goroutines do something at once: each goroutine puts a token in before working and takes it out after. When n tokens are in the buffer, the next goroutine must wait.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
const maxConcurrent = 2
sem := make(chan struct{}, maxConcurrent)
var running, peak atomic.Int32
var wg sync.WaitGroup
for range 6 {
wg.Go(func() {
sem <- struct{}{} // acquire a slot (blocks if 2 are busy)
now := running.Add(1)
for {
old := peak.Load()
if now <= old || peak.CompareAndSwap(old, now) {
break
}
}
running.Add(-1)
<-sem // release the slot
})
}
wg.Wait()
fmt.Println("tasks never ran more than", maxConcurrent, "at once:", peak.Load() <= maxConcurrent)
}tasks never ran more than 2 at once: true
struct{} is the empty struct type: it takes no memory, so it is the conventional element type when a channel only carries signals, not data.
Choosing a buffer size
- 0 (unbuffered) — the default. Use it when you want a guaranteed handoff between goroutines.
- 1 — common for "result" channels so the sender never gets stuck if the receiver has gone away.
- n — for a known number of results (
make(chan Result, len(tasks))) or to limit concurrency.
Tip: A buffer does not fix a design where the receiver is simply too slow — it only delays the moment the sender blocks. Start with unbuffered channels and add a buffer for a specific reason.
Test yourself
When does a send on make(chan int, 2) block?
- Always
- Never
- When two values are already waiting in the buffer
- When the channel is empty
In what order are values received from a buffered channel?
- Random
- Last in, first out
- First in, first out
- Sorted
Why is chan struct{} popular for signalling?
- It is faster to create
- The empty struct takes no memory
- It cannot be closed
- It is required by
select