HeadlinesBriefing favicon HeadlinesBriefing.com

Go Concurrency Distilled Mini-Book Overview

Hacker News •
×

This mini-book provides a brief overview of many concurrency topics in Go. Each topic comes with interactive examples — feel free to experiment with them by changing the code and clicking Run. There's also a PDF version with static examples.

This is a quick refresher on Go concurrency, not a beginner's guide. If you want to learn concurrency from the ground up with practical exercises, check out the other book — Gist of Go: Concurrency. The book is AI-free.

The foundation of concurrency in Go is goroutines — functions started with the go keyword. The Go runtime juggles these goroutines and distributes them among operating system threads running on CPU cores. Compared to OS threads, goroutines are lightweight, so you can create hundreds or thousands of them.

A wait group has a counter inside. Calling Add(n) increments it by n, while Done() decrements it by one. Wait() blocks the calling goroutine until the counter reaches zero.

This way, main waits for both workers to finish before it exits. Goroutines can pass values to each other through channels. A channel is like a window where one goroutine can throw something and another can catch it.

Sending a value through a channel is a synchronous operation. When the sending goroutine writes a value to the channel, it blocks and waits for someone to receive that value. Only then does it continue.

Output channel returning from a function and filling it within an internal goroutine is a common pattern. This allows the caller to receive values while the owning function retains control. Closing a channel signals to readers that all data has been sent.

The reader checks the channel's status with a second value "comma OK" when reading. If the channel is closed, the reader gets a zero value and a false status. Channel iteration range automatically reads the next value and checks if it is closed.

If closed, it exits the loop.