Concurrency in Go

Concurrency is where your programs learn to do many jobs at once.

In this chapter, you will:

  • start goroutines and wait for them
  • pass values between goroutines with channels
  • protect shared data with mutexes and atomics
  • find and prevent race conditions

What each lesson covers:

  • Goroutines: Concurrency in Go: concurrency vs parallelism, starting goroutines with go, waiting with WaitGroup, anonymous goroutines, what happens when main ends, and concurrent processing.
  • Channels: Go channels: create, send and receive, buffered channels and blocking, close, range and select, timeouts, channel directions, worker pools and done signals.
  • Synchronization: Coordinate goroutines safely: why synchronization is needed, sync.WaitGroup, sync.Mutex and RWMutex, sync/atomic, and how to detect and prevent race conditions.

This chapter has 3 lessons. Plan on about 80 minutes, with 9 exercises to check what you learned. Every example is real Go code: change it, run it again and compare the output, which is the fastest way to learn how each feature behaves.

Simple lesson: finish this chapter and you can use Go's best-known strength safely.

Lessons in this section

  1. Goroutines

    Concurrency in Go: concurrency vs parallelism, starting goroutines with go, waiting with WaitGroup, anonymous goroutines, what happens when main ends, and concurrent processing.

    • Explain concurrency and parallelism
    • Start goroutines with the go keyword
    • Wait for goroutines with a WaitGroup
    • Use anonymous goroutines safely
  2. Channels

    Go channels: create, send and receive, buffered channels and blocking, close, range and select, timeouts, channel directions, worker pools and done signals.

    • Create channels and send and receive values
    • Explain buffered channels, capacity and blocking
    • Use close, range and select
    • Add timeouts with time.After
  3. Synchronization

    Coordinate goroutines safely: why synchronization is needed, sync.WaitGroup, sync.Mutex and RWMutex, sync/atomic, and how to detect and prevent race conditions.

    • Explain why goroutines need synchronization
    • Use WaitGroup Add, Done and Wait
    • Protect shared data with Mutex and RWMutex
    • Use atomic operations for counters