Hi,
I am wondering what would the best way to exit channel iteration in the case of an error or once all the items are processed successfully. Example below won’t exit at all so the requirements are:
- 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.
Thanks
https://play.golang.org/p/jVTOQbexVER
package main
import (
"context"
"log"
)
func main() {
job := NewJob(5)
for i := 1; i <= 5; i++ {
go job.Add(i)
}
if err := job.Process(context.Background()); err != nil {
log.Fatalf("failed: %s", err.Error())
}
log.Println("all done")
}
type Job struct {
items chan int
}
func NewJob(size int) Job {
return Job{
items: make(chan int, size),
}
}
func (j Job) Add(job int) {
j.items <- job
}
func (j Job) Process(ctx context.Context) error {
for item := range 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
}