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()
}Report a problem with this exampleOpens a pre-filled issue on GitHub.