Skip to content

Instantly share code, notes, and snippets.

@sacko87
Created Feb 7, 2018
Embed
What would you like to do?
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