Сначала запускаем воркеры, потом создаем задачи. По окончанию задач надо закрыть канал.
package main
import (
"fmt"
"sync"
"time"
)
const (
jobsNum = 5
workersNum = 2
)
type Job struct {
id int
}
func worker(id int, jobChan <-chan Job, wg *sync.WaitGroup) {
for job := range jobChan {
process(id, job, wg)
}
}
func process(id int, job Job, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d, Job start: %d\n", id, job.id)
time.Sleep(1 * time.Second)
fmt.Printf("Worker %d, Job end: %d\n", id, job.id)
}
func main() {
fmt.Println("Start")
jobChan := make(chan Job, 10)
var wg sync.WaitGroup
wg.Add(jobsNum)
// start the workers
for i := 0; i < workersNum; i++ {
go worker(i, jobChan, &wg)
}
// enqueue jobs
for i := 0; i < jobsNum; i++ {
jobChan <- Job{
id: i,
}
}
close(jobChan)
wg.Wait()
fmt.Println("Done")
}
вывод
Start
Worker 1, Job start: 1
Worker 0, Job start: 0
Worker 0, Job end: 0
Worker 0, Job start: 2
Worker 1, Job end: 1
Worker 1, Job start: 3
Worker 0, Job end: 2
Worker 0, Job start: 4
Worker 1, Job end: 3
Worker 0, Job end: 4
Done