Skip to content

Instantly share code, notes, and snippets.

@developernaren
Created July 20, 2021 03:40
Show Gist options
  • Save developernaren/4f7e58f9495ed3fd6efeb6ecd0df96be to your computer and use it in GitHub Desktop.
Save developernaren/4f7e58f9495ed3fd6efeb6ecd0df96be 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(3) // 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
for j := 1; j <= 50; j++ {
number := <-numberCh
fmt.Println(fmt.Sprintf("receiving %d", number))
}
}(wg) // passing the waitGroup, so that we can make it as done, when time comes
go func(wg *sync.WaitGroup) {
defer wg.Done()
err := <-errCh
if err != nil {
fmt.Println("errored")
close(errCh)
}
}(wg)
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment