Created
July 20, 2021 03:25
-
-
Save developernaren/0b7673dc7c137c0499034beacc93e409 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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