Generic Concurrent Runner
Source: Custom
Topics: Generics, Goroutines, Channels, Context, Benchmarks
Problem
Implement a generic Run function that executes a slice of tasks concurrently and collects their results.
Requirements:
- Accept any input type
T and output type R using Go generics.
- Limit concurrency to
n workers (semaphore pattern).
- Respect
context.Context cancellation — stop early if the context is cancelled.
- Preserve the original order of results.
- Return all errors without stopping other workers (collect, don't abort).
Signature:
func Run[T, R any](ctx context.Context, tasks []T, n int, fn func(context.Context, T) (R, error)) ([]R, []error)
Key concepts
- Semaphore via buffered channel:
make(chan struct{}, n) limits concurrent goroutines.
- WaitGroup: coordinates when all goroutines finish.
- Pre-allocated result slice: index-safe writes avoid a mutex for results.
- Context propagation: pass
ctx into each fn call so the task itself can cancel.
Run
go test -v -bench=. -benchmem ./challenges/concurrency/generic-runner/
Sign in to submit your solution.