// HACKER NEWS — CYBERSECURITY
Go Concurrency Distilled
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 my other book — Gist of Go: Concurrency.
Goroutines •
Channels •
Select •
Pipelines •
Time •
Context •
Wait groups •
Data races •
Race conditions •
Mutexes •
Semaphores •
Signaling •
Run once •
Object pool •
Atomics •
Testing •
Scheduling •
Diagnostics •
Final thoughts
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.
Goroutines are completely independent. The main function is also a goroutine, but it starts implicitly when the program starts. When main ends, other goroutines also shut down.
We use a wait group (sync.WaitGroup) to wait for goroutines to finish in the example above. 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 (in this case, main) until the counter reaches zero. This way, main waits for both workers to finish before it exits.
WaitGroup.Go automatically increments the wait group counter, runs a function in a goroutine, and decrements the counter when it's done:
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 (ch <- val), it blocks and waits for someone to receive that value (<-ch). Only then does it continue.