Fixed Worker Pool
Process a stream of jobs with a fixed number of goroutines, bounded channels and graceful completion.
Code
package workers
import (
"context"
"sync"
)
func Run(ctx context.Context, workers int, jobs <-chan int, handle func(context.Context, int) error) error {
if workers <= 0 {
return nil
}
var wg sync.WaitGroup
wg.Add(workers)
for i := 0; i < workers; i++ {
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobs:
if !ok {
return
}
_ = handle(ctx, job)
}
}
}()
}
wg.Wait()
return ctx.Err()
}How it works
Rather than application code, this file declares a pipeline: 0 jobs split into 0 steps.
Iteration is driven by for i := 0; i < workers; i++ and for.
The file declares a reusable Run(ctx, workers, jobs, handle) rather than a runnable program. The guard clause returns nil immediately when workers <= 0. A sync.WaitGroup with wg.Add(workers) tracks the pool; each goroutine loops on a select that returns on <-ctx.Done() and otherwise receives from jobs — a closed channel (ok == false) ends that worker, while each delivered job is handed to handle(ctx, job). defer wg.Done() releases the slot, and after wg.Wait() the function returns ctx.Err(), which is nil unless the context was cancelled.
Statements that matter
return ctx.Err()
var wg sync.WaitGroup
defer wg.Done()
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `context`, `sync`. The file defines `Run` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.