Buffered channel
- Go course
- Intermediate
- Lesson 11/80
- 4 min
Learn buffered channels and the capacity concept.
Buffered channel
A buffered channel holds a fixed number of values in a buffer: ch := make(chan int, 3). The sender does not block until the buffer is full; sends complete even without a receiver.
When the buffer is full the sender blocks; when empty the receiver blocks. This improves throughput in producer-consumer patterns. But a large buffer can make ordering unclear.
Buffer behavior
Buffered channel behavior boils down to four points:
- Sender does not block until buffer is full; no receiver needed yet
- Receiver blocks when buffer is empty; it waits for data
cap(ch)gives the buffer size, the total capacitylen(ch)gives the filled slot count, pending data
A buffered channel gives asynchronous starts but no ordering guarantee; choose the size carefully.
Practice Use a buffered channel
Inside main, add a make(chan string, 2) call and print buffered ran with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ch := make(chan string, 2)
ch <- "tamponlu çalıştı"
fmt.Println(<-ch)
}Expected output
tamponlu çalıştı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many values can make(chan int, 3) buffer?
- 2
- 1
- 3 Correct answer
- Unlimited
Explanation: The buffer size is the second argument.
2 Creating a buffered channel
ch := make(chan int, ____)
ch := make(chan int, 3)
Explanation: The second argument is the buffer size.
3 Match buffered channel
| Term | Meaning |
|---|---|
make(chan int, 3) |
Buffered |
cap(ch) |
Buffer size |
len(ch) |
Filled count |
block |
When full |