Skip to content

Instantly share code, notes, and snippets.

@slifer2015
Last active May 19, 2018 11:35
Show Gist options
  • Save slifer2015/c15a2333c52585cd6149e3309c7b364a to your computer and use it in GitHub Desktop.
Save slifer2015/c15a2333c52585cd6149e3309c7b364a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
"errors"
"math/rand"
)
func handler(a []string) error {
errChan := make(chan error, len(a))
sem := make(chan int, 4)
var wg sync.WaitGroup
wg.Add(len(a))
for _, val := range a {
go func(i string) {
defer wg.Done()
sem <- 1
if err := fetch(i); err != nil {
errChan <- err
}
<-sem
}(val)
}
wg.Wait()
close(errChan)
return <-errChan
}
func fetch(a string) error {
fmt.Println("fetch func ...")
time.Sleep(1 * time.Second)
if rand.Intn(10)%2 == 0 {
return nil
}
return errors.New("error occurred")
}
func main() {
input := []string{"a", "b", "c"}
handler(input)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment