Skip to content

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

  1. Try it yourself first — rename the solution aside and re-implement from the prompt below.
  2. Run go test -race ./... from this directory.
  3. Compare with the provided solution; log differences in your day note's "Mistakes" section.

Prompts

  • safecounter: implement a Counter safe for concurrent use, guarded by a sync.RWMutex. Methods: Inc(), Add(delta int64), Value() int64 (read lock), and Reset() int64 returning the previous value. The zero value must be usable; it must not be copied after use (pass *Counter). A concurrent Inc test must yield an exact deterministic total under -race.
  • oncecache: implement Cache.Get(key string, loader func(string) int) int that runs loader exactly once per distinct key even under heavy concurrency, caching the result. Combine sync.Map.LoadOrStore (one *entry per key) with a per-key sync.Once. A test must assert loader ran exactly once per key across many goroutines.
  • atomicgate: implement (1) a Gate whose Trip() returns true for only the first caller (use CompareAndSwap), and (2) a MaxTracker whose Observe(v int64) keeps the running maximum via a CAS retry loop. Both must be lock-free (sync/atomic only) 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 ./....


Exercises