This works for me. Corrected, I did a wrong 'un earlier
package main
import (
"context"
"log"
"sync"
)
func main() {
job := NewJob(5)
for i := 1; i <= 5; i++ {
job.wg.Add(1)
go job.Add(i)
}
job.wg.Wait()
if err := job.Process(context.Background()); err != nil {
log.Fatalf("failed: %s", err.Error())
}
log.Println("all done")
}
type Job struct {
items chan int
wg *sync.WaitGroup
}
func NewJob(size int) Job {
return Job{
items: make(chan int, size),
wg: &sync.WaitGroup{},
}
}
func (j Job) Add(job int) {
j.items <- job
j.wg.Done()
}
func (j Job) Process(ctx context.Context) error {
for len(j.items) > 0 {
item := <-j.items
log.Println(item)
// - All items are handled in a goroutine.
// - Exit as soon as an error is returned.
// - Exit when all the items are processed
// - If an error occurs, all other running goroutines.
}
return nil
}