Skip to content

Instantly share code, notes, and snippets.

@srleyva
Created May 23, 2019 13:37
Show Gist options
  • Save srleyva/65608c95f8e6ba310d240c2bc9dbb1a5 to your computer and use it in GitHub Desktop.
Save srleyva/65608c95f8e6ba310d240c2bc9dbb1a5 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"time"
)
type Job struct {
Name string
Finished bool
}
func processJob(job Job, c chan Job) {
r := rand.Intn(10)
fmt.Printf("Job %s has started and will take %d seconds\n", job.Name, r)
time.Sleep(time.Duration(r) * time.Second)
if r%2 != 0 {
job.Finished = true
}
c <- job
}
func main() {
c := make(chan Job)
a := []Job{
Job{"a", false},
Job{"b", false},
Job{"c", false},
Job{"d", false},
Job{"e", false},
Job{"f", false},
}
for _, job := range a {
go processJob(job, c)
}
finished := 0
errors := 0
for i := 0; i < len(a); i++ {
select {
case job := <-c:
if job.Finished {
finished++
fmt.Printf("Job %s finished successfully!\n", job.Name)
} else {
errors++
fmt.Printf("Job %s had error\n", job.Name)
}
}
}
fmt.Printf("Job stats: %d/%d finished with %d errors\n", finished, len(a), errors)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment