Fixed Worker Pool

Process a stream of jobs with a fixed number of goroutines, bounded channels and graceful completion.

GoResilience

Code

snippet
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()
}