Skip to content

Instantly share code, notes, and snippets.

@gabibeyer
Last active February 18, 2019 19:52
Show Gist options
  • Save gabibeyer/a18f60206a8227181d2fd645f40560a3 to your computer and use it in GitHub Desktop.
Save gabibeyer/a18f60206a8227181d2fd645f40560a3 to your computer and use it in GitHub Desktop.
A fix that uses a third channel
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func getStrings(fileName string) (string, error) {
time.Sleep(400 * time.Millisecond)
r := rand.Intn(100)
if r%2 != 0 {
return "", fmt.Errorf("FAKE ERROR: %s", fileName)
}
return fileName, nil
}
func main() {
rand.Seed(time.Now().UnixNano())
var wg sync.WaitGroup
workers := 4
wg.Add(workers)
jobCh := make(chan string)
errCh := make(chan error)
wgCh := make(chan struct{})
go func() {
for i := 0; i < workers; i++ {
go func() {
defer wg.Done()
for fileName := range jobCh {
in, err := getStrings(fileName)
if err != nil {
errCh <- err
fmt.Println(err)
break
}
fmt.Println("string processed: ", in)
}
}()
}
wg.Wait()
close(wgCh)
}()
testStrings := []string{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "", "", "", "", "", ""}
b := false
for _, s := range testStrings {
if b {
break
}
select {
case ch := <-errCh:
fmt.Println("error found: ", ch)
b = true
case jobCh <- s:
fmt.Println("adding job: ", s)
case <-wgCh:
fmt.Println("done")
return
}
}
close(jobCh)
select {
case ec := <-errCh:
fmt.Println("f: ", ec)
case <-wgCh:
fmt.Println("wg done")
break
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment