liveBook · Manning

Buffered channel

As explained in Go in Action, Second Edition

A buffered channel is a channel with storage for a specified number of values that can be sent before a send operation blocks.

A buffered channel lets a producer send values without waiting for each value to be received. Its capacity sets how many values can be queued; once the buffer is full, another send blocks until a receiver takes a value. In Go, `make(chan *gofeed.Article, 10)` creates a channel with room for ten article pointers. section 9.4

func (a *App) fetchFeed(ctx context.Context, url string) {
...
 fmt.Println("fetched: ", url)
 out := make(chan *gofeed.Article, 10) #1
 go a.saveFeed(out)
 ...
}

The article-ingestion channel uses a capacity of ten so fetching can continue while a separate goroutine saves articles. section 9.4

The same pattern works at the application boundary. An application can queue feed URLs in a buffered channel, then have a background goroutine receive them. A worker pool extends this design: workers share one buffered URL channel and take queued work as they become available. Buffer capacity controls how much work can wait; the number of workers controls how many workers receive from that queue. section 9.4 section 9.5.1

Listing 9.21 main.go: Worker pools
type WorkerPool struct {
 workers []*Worker #1
 incomingFeeds chan string #2
}

func NewWorkerPool(app *App, count int) *WorkerPool {
 wp := &WorkerPool{}
 wp.incomingFeeds := make(chan string, 100) #3
 for i := range count {
  w := NewWorker(app, incomingFeeds) #4
  append(wp.workers, w)
 }
 return wp
}

func (wp *WorkerPool) Submit(url string) {
 wp.incomingFeeds <- url #5
}

func (wp *WorkerPool) Stop() {
 close(wp.incomingFeeds)
}

The worker-pool listing illustrates a shared URL channel with capacity 100, a submission method that sends to it, and workers that receive from it. section 9.5.1

How Go in Action, Second Edition covers it

How deep it goes
Explains capacity and send blocking through channel construction and application examples, without detailing channel internals.
Examples
Demonstrates ten-slot article buffering, a five-slot application feed queue, and a 100-slot worker-pool queue.
What it assumes
Assumes working knowledge of Go channels, goroutines, and structs while introducing buffering through changes to channel capacity.
What you can do after
Build it from scratch by choosing a channel capacity and using the channel as a queue between feed producers and workers.
How it connects
Connects buffering to goroutines, channel directionality, producer–consumer workflows, and worker pools.

Also explained in

Compare how 3 books explain buffered channel →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.