Skip to content

Instantly share code, notes, and snippets.

@developernaren
Created July 20, 2021 03:25
Show Gist options
  • Save developernaren/0b7673dc7c137c0499034beacc93e409 to your computer and use it in GitHub Desktop.
Save developernaren/0b7673dc7c137c0499034beacc93e409 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
)
func main() {
errGroup, ctx := errgroup.WithContext(context.Background())
numberCh := make(chan int, 50)
errGroup.Go(func() error {
defer close(numberCh)
for i := 1; i <= 50; i++ {
if i == 30 {
return fmt.Errorf("30 is not allowed")
}
numberCh <- i
fmt.Println(fmt.Sprintf("sending %d", i))
}
return nil
})
errGroup.Go(func() error {
for j := 1; j <= 50; j++ {
select {
case <-ctx.Done():
return ctx.Err()
case number := <-numberCh:
fmt.Println(fmt.Sprintf("receiving %d", number))
}
}
return nil
})
err := errGroup.Wait()
if err != nil {
fmt.Println(err)
}
fmt.Println("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment