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 holds a specified number of values, allowing producers and consumers to work at different paces. A send blocks when the buffer is full and resumes when a value is received and space becomes available. section 9.4

Buffering articles

A feed fetcher can send articles to a channel while a separate goroutine saves them. Increasing the channel capacity lets the fetcher queue multiple articles instead of waiting for each receive. The capacity limits queued values, not necessarily articles still being processed. 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 second argument to make sets the article channel’s capacity to 10; saveFeed consumes values concurrently. section 9.4

A buffered channel can also serve as a shared work queue. A worker pool submits feed URLs to the channel, and workers receive URLs from that common queue. Buffering separates submission from execution until the queue fills; more workers can process feeds concurrently. section 9.5.1

How Go in Action, Second Edition covers it

How deep it goes
Explains capacity and blocking through application examples, without examining channel internals.
Examples
Shows article ingestion with a capacity of 10 and a shared feed-URL queue for workers.
What you can do after
Apply it in Go to queue values between producers and consumers or share work among workers.
How it connects
Connects buffered channels with producer-consumer workflows, channel directionality, 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.