wait for concurrent workers to finish before exiting

Wait for the two receiving goroutines to complete using a wait group. Use one wait group to wait for both goroutines.

Close the channels after sending all values so that the loops in the receiving goroutines exit.

There’s no need to wait for the sending goroutine. The grouting competes all of it’s work before the other coroutines complete.

worker1CH := make(chan int, 1)
worker2CH := make(chan int, 1)

var wg sync.WaitGroup
wg.Add(2)  // <-- wait for the two receiving goroutines.

// worker for even numbers
go func(wg *sync.WaitGroup, in chan int) {
    defer wg.Done() // <--- add this line
    for i := range in {
        log.Print(i)
    }
}(&wg, worker1CH)

// worker for odd numbers
go func(wg *sync.WaitGroup, in chan int) {
    defer wg.Done() <-- add this line
    for i := range in {
        log.Print(i)
    }
}(&wg, worker2CH)

// sender which sends even numbers to worker1CH, and odd numbers to worker2CH
go func(evenChan chan int, oddChan chan int) {

    defer close(evenChan) // <-- close channel so that receiver exits loop
    defer close(oddChan)  // <-- ditto

    data := rand.Perm(10)
    for _, i := range data {
        switch i % 2 {
        case 0:
            evenChan <- i
        default:
            oddChan <- i
        }
    }
}(worker1CH, worker2CH)

wg.Wait()

Run the example on the Go Playground.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top