Singleflight
Source: Custom (mirrors golang.org/x/sync/singleflight with generics)
Topics: sync.Mutex, sync.WaitGroup, Goroutines, Generics
Problem
Implement a Group[T] that deduplicates concurrent in-flight calls by key.
Requirements:
- If multiple goroutines call
Do with the same key simultaneously, only the first runs fn.
- All other callers block until
fn returns and receive the same result.
- The third return value (
shared bool) is true for callers that waited for a shared result.
- After
fn completes, the key is removed — future calls run fn again.
- Errors are shared too — all waiters receive the same error.
Type:
type Group[T any] struct { ... }
func (g *Group[T]) Do(key string, fn func() (T, error)) (val T, err error, shared bool)
Key concepts
- In-flight call struct: holds a
sync.WaitGroup, the result, and the error.
- sync.Mutex: protects the map of in-flight calls; held only while updating the map (not while
fn runs).
- WaitGroup: the first caller adds 1 before releasing the lock; others call
wg.Wait() then read the result.
- Lazy map init: initialise
inflight on first use inside Do to avoid requiring a constructor.
Run
go test -v -race -bench=. ./challenges/concurrency/singleflight/
Sign in to submit your solution.