Table of Contents
Month 3 · Week 2 — Exercises¶
Practice for the sync toolbox: mutexes, WaitGroup, Once, and sync/atomic.
Each folder is its own package with a solution and table-driven tests. Standard
library only. Always run under the race detector — concurrency bugs hide
from a plain go test.
| Exercise | Concept | Day | Run tests |
|---|---|---|---|
safecounter/ |
sync.RWMutex-guarded counter, no-copy rule |
064 | go test -race ./safecounter |
oncecache/ |
once-per-key memoisation: sync.Map + per-key sync.Once |
066 | go test -race ./oncecache |
atomicgate/ |
lock-free one-shot gate + CAS retry-loop max tracker | 067 | go test -race ./atomicgate |
How to use¶
- Try it yourself first — rename the solution aside and re-implement from the prompt below.
- Run
go test -race ./...from this directory. - Compare with the provided solution; log differences in your day note's "Mistakes" section.
Prompts¶
- safecounter: implement a
Countersafe for concurrent use, guarded by async.RWMutex. Methods:Inc(),Add(delta int64),Value() int64(read lock), andReset() int64returning the previous value. The zero value must be usable; it must not be copied after use (pass*Counter). A concurrentInctest must yield an exact deterministic total under-race. - oncecache: implement
Cache.Get(key string, loader func(string) int) intthat runsloaderexactly once per distinct key even under heavy concurrency, caching the result. Combinesync.Map.LoadOrStore(one*entryper key) with a per-keysync.Once. A test must assertloaderran exactly once per key across many goroutines. - atomicgate: implement (1) a
GatewhoseTrip()returnstruefor only the first caller (useCompareAndSwap), and (2) aMaxTrackerwhoseObserve(v int64)keeps the running maximum via a CAS retry loop. Both must be lock-free (sync/atomiconly) and correct under concurrent stress.
Results¶
| Exercise | Tests | Status |
|---|---|---|
| safecounter | TestAddTableDriven, TestConcurrentInc, TestReset |
✅ |
| oncecache | TestGetCaches, TestLoaderRunsOncePerKey |
✅ |
| atomicgate | TestGateSingleWinner, TestMaxTrackerTableDriven, TestMaxTrackerConcurrent |
✅ |
Tip: run all of Week 2 at once with
go test -race ./....