var wg sync.WaitGroup for i := 0; i < numWorkers; i++ { wg.Add(1) gofunc(id int) { defer wg.Done() for job := range jobs { results <- fmt.Sprintf("worker %d processed job %d", id, job) } }(i) }
for j := 1; j <= 20; j++ { jobs <- j } close(jobs)
funcworkerWithCancel(ctx context.Context, jobs <-chanint, results chan<- int, wg *sync.WaitGroup) { defer wg.Done() for { select { case v, ok := <-jobs: if !ok { return } results <- v * 2 case <-ctx.Done(): return } } }
funcmain() { ctx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup jobs := make(chanint, 100) results := make(chanint, 100)
for i := 1; i <= 5; i++ { wg.Add(1) go workerWithCancel(ctx, jobs, results, &wg) }
for j := 1; j <= 10; j++ { jobs <- j } close(jobs)