Go Tutorial: Concurrency
Do multiple things at once. Goroutines and channels are Go's superpower — lightweight, safe, and elegant.
Go was built for this
Most languages treat concurrency as an add-on. You reach for a library, learn a callback system, or fight with threads and locks.
Go was designed from day one with concurrency in mind. A goroutine costs less than 2KB of memory. You can run thousands of them. Channels let them communicate safely without shared memory bugs.
The famous Go proverb sums it up:
Do not communicate by sharing memory. Share memory by communicating.
This chapter is why people fall in love with Go. Fourteen steps.
What you'll learn in this Go concurrency tutorial
This interactive Go tutorial has 14 hands-on exercises. Estimated time: 28 minutes.
- What is a goroutine — A goroutine is a function that runs concurrently with other functions.
- Channels — communicate between goroutines — A channel is a pipe between goroutines. One goroutine sends a value, another receives it.
- Send and receive multiple values — A channel can send as many values as you need. The receiver collects them in order.
- WaitGroup — wait for goroutines to finish — `sync.WaitGroup` lets you wait for a group of goroutines to complete.
- Buffered channels — A regular channel blocks until the receiver is ready. A buffered channel has a queue — you can send without blocking unt…
- Range over a channel — You can loop over a channel with `range` — it receives values until the channel is closed.
- select — handle multiple channels — `select` is like a `switch` for channels. It waits for whichever channel is ready first:
- select with default — non-blocking — Add a `default` case to `select` to make it non-blocking. If no channel is ready, the default runs immediately.
- Mutex — protect shared data — When multiple goroutines access the same variable, you get a race condition — unpredictable results.
- Done channel — signal cancellation — A done channel signals goroutines to stop.
- Worker pool — A worker pool runs a fixed number of goroutines to process jobs from a queue channel.
- Race condition — spot and fix it — A race condition happens when two goroutines access the same variable without synchronisation. The result is unpredictab…
- Goroutines are cheap — A goroutine starts with about 2KB of stack memory (growing as needed). You can run thousands without issue.
- Build a concurrent pipeline — No starter code.
Go Concurrency concepts covered
- Go was built for this