Canonical guidance

Use when

Avoid

Preferred pattern

func Run(ctx context.Context, workers int, jobs <-chan Job) error {
	var wg sync.WaitGroup

	for i := 0; i < workers; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for {
				select {
				case <-ctx.Done():
					return
				case job, ok := <-jobs:
					if !ok {
						return
					}
					job.Process(ctx)
				}
			}
		}()
	}

	wg.Wait()
	return ctx.Err()
}

Anti-pattern

Explanation: This anti-pattern is common because goroutine-per-task is easy to write, but it defeats the whole resource-control purpose of a worker pool.

Why

Related pages

Sources