Skip to content

Instantly share code, notes, and snippets.

@developernaren
Created July 20, 2021 03:55
Show Gist options
  • Save developernaren/d2529139d0633308fab3a856b4a1b98e to your computer and use it in GitHub Desktop.
Save developernaren/d2529139d0633308fab3a856b4a1b98e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
func main() {
wg := new(sync.WaitGroup) //create a wait group
wg.Add(2) // we know we are going to wait for two go routines
numberCh := make(chan int, 50)
errCh := make(chan error)
go func(wg *sync.WaitGroup) {
defer wg.Done() // first one done
for i := 1; i <= 50; i++ {
if i == 30 {
errCh <- fmt.Errorf("30 is not allowed")
close(numberCh) // because we are no longer sending to this channel, we should close this channel
break
}
numberCh <- i
fmt.Println(fmt.Sprintf("sending %d", i))
}
}(wg) // passing the waitGroup, so that we can make it as done, when time comes
go func(wg *sync.WaitGroup) {
defer wg.Done() // first one done
RLoop:
for j := 1; j <= 50; j++ {
select {
case err := <-errCh:
close(errCh)
fmt.Println(fmt.Sprintf("we have to break because %s", err.Error()))
break RLoop
case number := <-numberCh:
fmt.Println(fmt.Sprintf("receiving %d", number))
}
}
}(wg) // passing the waitGroup, so that we can make it as done, when time comes
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment