Buffered Channels
In this page:
Creating a Buffered Channel
Passing a second argument to make when creating a channel gives it a buffer, allowing that many values to be sent without a receiver being ready at that exact moment.
Example: Creating a Buffered Channel
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2 // does not block: buffer has room for 2
fmt.Println(<-ch)
fmt.Println(<-ch)
}
Login to try C/C++/Java/PHP code in the editor
Blocking Once the Buffer Is Full
A buffered channel isn't unlimited -- once its buffer is full, the next send still blocks until a receiver frees up space by taking a value out.
Example: Blocking Once the Buffer Is Full
package main
import "fmt"
func main() {
ch := make(chan int, 1)
ch <- 10
go func() {
fmt.Println("received:", <-ch) // frees buffer space
}()
ch <- 20 // would block until the goroutine above receives
fmt.Println("done")
}
Login to try C/C++/Java/PHP code in the editor
Checking Length and Capacity
len(ch) tells you how many values are currently sitting in the buffer waiting to be received, while cap(ch) tells you the buffer's total capacity set when the channel was created.
Example: Checking Length and Capacity
package main
import "fmt"
func main() {
ch := make(chan int, 3)
ch <- 1
ch <- 2
fmt.Println("len:", len(ch), "cap:", cap(ch))
}
Login to try C/C++/Java/PHP code in the editor
- Assuming a buffered channel never blocks -- it still blocks once the buffer is full on send, or empty on receive.
- Choosing an arbitrary buffer size without reasoning about the actual production/consumption rate, masking a design problem instead of solving it.
- Confusing a channel's capacity (cap) with how many values are currently queued in it (len).
- make(chan Type, n) creates a buffered channel that can hold up to n values without a receiver ready.
- A send on a buffered channel only blocks once the buffer is full; a receive only blocks once it's empty.
- len(ch) reports how many values are currently queued; cap(ch) reports the buffer's total capacity.
- Buffered channels help decouple producers and consumers running at slightly different speeds.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: