Last active
May 19, 2018 11:35
-
-
Save slifer2015/c15a2333c52585cd6149e3309c7b364a to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"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