Skip to content

Instantly share code, notes, and snippets.

@advincze
Created November 26, 2014 07:01
Show Gist options
  • Save advincze/704d4b98d61ccd7a8145 to your computer and use it in GitHub Desktop.
Save advincze/704d4b98d61ccd7a8145 to your computer and use it in GitHub Desktop.
work dispatcher
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "processing job", j)
time.Sleep(time.Duration(id) * time.Second)
results <- j
}
fmt.Println("worker", id, "done")
}
func resultCollector(results <-chan int, wg *sync.WaitGroup) {
for r := range results {
fmt.Println("got result", r)
wg.Done()
}
}
func main() {
wg := new(sync.WaitGroup)
jobs := make(chan int)
results := make(chan int)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
go resultCollector(results, wg)
for j := 1; j <= 9; j++ {
wg.Add(1)
jobs <- j
}
close(jobs)
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment