Exiting channel iteration

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
}

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
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.