Concurrency Model
What you will learn
- distinguish concurrency from parallel execution;
- identify ownership, completion, and cancellation;
- recognise data races;
Concurrency means structuring a program so several tasks can make progress during the same period. Parallelism means tasks literally execute at the same instant on different CPU cores.
A concurrent program may or may not run in parallel. The Go runtime decides how runnable goroutines are scheduled onto operating-system threads.
Why use concurrency?
Concurrency is useful when work spends time waiting or when independent tasks can proceed separately:
- serving many network requests;
- reading from several services;
- processing a stream of jobs;
- keeping a user interface responsive;
- coordinating background work and shutdown.
Concurrency is not automatically faster. Goroutines, communication, scheduling, and synchronisation all have costs.
The three questions
Before starting a goroutine, answer:
- Who owns the data? Shared mutation needs a clear rule.
- How does the work stop? Every long-lived goroutine needs a cancellation or completion path.
- Who waits for it? The program must not exit while required work is unfinished.
Two coordination styles
Communicate ownership
One goroutine owns data. Other goroutines send it requests through channels. This can make ownership clear and avoid shared mutation.
Protect shared state
Several goroutines access the same data, protected by tools such as sync.Mutex. This is often simpler for caches, counters, and small critical sections.
Neither style is always superior. Choose the one that makes ownership and lifetime easiest to understand.
Race conditions
A data race occurs when goroutines access the same memory concurrently, at least one access writes, and there is no proper synchronisation.
count := 0
go func() { count++ }()
go func() { count++ }()
This is unsafe. count++ contains a read, calculation, and write; the operations can overlap and lose an update.
The race detector can find many real races during tests:
go test -race ./...
It only detects code paths that actually run, so it complements good design rather than replacing it.
A useful rule
Next: Goroutines.
Practice
Before starting a background goroutine, answer: who waits for it, how does it report failure, and how is it cancelled?
errgroup or WaitGroup), an explicit result/error path, and a cancellation signal such as context.Context. If none exists, the goroutine can leak or fail invisibly.Summary
- Concurrency structures overlapping work; parallelism is simultaneous execution.
- Every goroutine needs ownership, completion, and cancellation rules.
- Shared mutable state requires synchronization or single-owner confinement.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.