Concurrency Best Practices
Start with Concurrency Best Practices
In this lesson, explore concurrency best practices through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of concurrency best practices.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Keep ownership simple, avoid unbounded goroutine creation, use context for cancellation, wait for completion, and test with the race detector. Treat channels, locks and wait groups as explicit contracts, not decoration.
Correct concurrent code is easier to reason about when each task has one role, one stopping path and a clear result handoff.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
results := make(chan int, 2)
var wg sync.WaitGroup
for _, n := range []int{2, 4} {
wg.Add(1)
go func(value int) {
defer wg.Done()
select {
case results <- value * value:
case <-ctx.Done():
}
}(n)
}
wg.Wait()
close(results)
sum := 0
for value := range results {
sum += value
}
fmt.Println("Squares sum:", sum)
}
Output
Squares sum: 20Trace what the program does
Workers have explicit completion via WaitGroup and a cancellation path for sending. The buffered channel allows both results and main sums 4+16 to 20.
Avoid common mistakes
- A done channel is not enough if the worker ignores it during potentially blocking sends.
- Review shutdown paths as carefully as the happy path.
Try it yourself
Add another worker and explain how you would shut them all down if the caller stopped early.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Concurrency Best Practices in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.