Skip to content

Commit

Permalink
[ERRGROUPS] adds errgroup example
Browse files Browse the repository at this point in the history
  • Loading branch information
PatAkil committed Nov 1, 2024
1 parent 1af048b commit f9171d3
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
52 changes: 52 additions & 0 deletions examples/channels/errgroups/errgroups.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package main

import (
"fmt"
"golang.org/x/sync/errgroup"
"log"
)

// START OMIT
func sum(nums []int, resultChannel chan<- int) {
total := 0
for _, v := range nums {
total += v
}
resultChannel <- total
}

func doit() error {
var g errgroup.Group
resultChannel := make(chan int, 2)

numSets := [][]int{{1, 2, 3}, {4, 5, 6}}

for _, nums := range numSets {
nums := nums // no longer needed after 1.23
g.Go(func() error {
sum(nums, resultChannel)
return nil
})
}
// First error will cancel all pending go routines
if err := g.Wait(); err != nil {
return err
}
close(resultChannel)

totalSum := 0
for result := range resultChannel {
totalSum += result
}
fmt.Printf("sum=%d\n", totalSum)
return nil
}

// END OMIT

func main() {
err := doit()
if err != nil {
log.Fatal(err)
}
}
6 changes: 6 additions & 0 deletions go-training.slide
Original file line number Diff line number Diff line change
Expand Up @@ -1536,6 +1536,12 @@ Alternative approaches:

#----------------------------------------------

* Divide the work <channels + errgroup>

.play -edit examples/channels/errgroups/errgroups.go /START OMIT/,/END OMIT/

#----------------------------------------------

* Select example <select>
- Wait for events on multiple channels

Expand Down

0 comments on commit f9171d3

Please sign in to comment.