Skip to content

Instantly share code, notes, and snippets.

@sacko87
Created February 7, 2018 14:08
Show Gist options
  • Save sacko87/dd7d4db7a26057ae843b77259d34c66e to your computer and use it in GitHub Desktop.
Save sacko87/dd7d4db7a26057ae843b77259d34c66e to your computer and use it in GitHub Desktop.
package main
import (
"log"
"sync"
)
type Job struct {
source int
}
type Result struct {
Job
target int
}
var jobs = make(chan Job, 10)
var results = make(chan Result, 10)
func worker(w *sync.WaitGroup) {
for job := range jobs {
results <- Result{job, job.source * 2}
}
w.Done()
}
func allocate(n int) {
for i := 0; i < n; i++ {
jobs <- Job{i}
}
close(jobs)
}
func result(done chan bool) {
for result := range results {
log.Println(result.source, " ", result.target)
}
done <- true
}
func createWorkerPool(n int) {
var w sync.WaitGroup
for i := 0; i < n; i++ {
w.Add(1)
go worker(&w)
}
w.Wait()
close(results)
}
func main() {
var done = make(chan bool, 1)
go allocate(10)
go result(done)
createWorkerPool(2)
<- done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment