Table of Contents
Month 3 · Week 3 — Exercises¶
Practice for the concurrency patterns: worker pools, fan-out/fan-in,
pipelines, bounded parallelism, semaphores, and context cancellation. Each
folder is its own package with a solution and table-driven tests. Standard
library only. Always run under the race detector — pattern bugs (lost
sends, double-close, leaked goroutines) hide from a plain go test.
| Exercise | Concept | Day | Run tests |
|---|---|---|---|
semaphore/ |
counting semaphore from a buffered channel; TryAcquire, AcquireCtx |
074 | go test -race ./semaphore |
boundedmap/ |
order-preserving bounded parallel map with first-error + context cancel |
074–075 | go test -race ./boundedmap |
taskgroup/ |
stdlib mini-errgroup: Go/Wait, SetLimit, WithContext |
076 | go test -race ./taskgroup |
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¶
- semaphore: implement a counting
Semaphore(constructed withNew(n),nclamped to ≥ 1) backed by a buffered channel. Methods:Acquire()(blocks),Release()(panics if called without a matching acquire),TryAcquire() bool(never blocks), andAcquireCtx(ctx) error(returnsctx.Err()if the context is done first). A stress test must assert the number of concurrent holders never exceedsn. - boundedmap: implement a generic
Map[T, R](ctx, inputs, workers, fn) ([]R, error)that appliesfnwith at mostworkersgoroutines, preserving input order (write by index, no locks). The firstfnerror, or a cancelledctx, must stop work promptly and be returned. Derive a child context so the first error cancels the rest;defer cancel()to avoid a leak; the feeder mustselectonctx.Done()so it never blocks after workers exit. - taskgroup: implement a stdlib
Groupmirroringx/sync/errgroup:Go(func() error),Wait() errorreturning the first error,WithContext(ctx)cancelling on first failure (and onWait), andSetLimit(n)capping concurrency (acquire a slot inGo, release on return). Usesync.Onceso only the first error is kept.
Results¶
| Exercise | Tests | Status |
|---|---|---|
| semaphore | TestNeverExceedsLimit, TestTryAcquire, TestAcquireCtxCancelled, TestAcquireCtxSucceeds, TestReleaseWithoutAcquirePanics |
✅ |
| boundedmap | TestMapPreservesOrder, TestMapRunsFnOncePerInput, TestMapReturnsFirstError, TestMapHonoursCancelledContext |
✅ |
| taskgroup | TestAllSucceed, TestFirstErrorReturnedAndContextCancelled, TestContextCancelledAfterWaitEvenOnSuccess, TestSetLimitBoundsConcurrency, TestWaitReturnsFirstOfManyErrors |
✅ |
Tip: run all of Week 3 at once with
go test -race ./....