Skip to content

Instantly share code, notes, and snippets.

@whym
Last active April 1, 2016 08:35
Show Gist options
  • Save whym/9d57a9bf51e025cb2e9c70fc5b3ca8c4 to your computer and use it in GitHub Desktop.
Save whym/9d57a9bf51e025cb2e9c70fc5b3ca8c4 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
"math/rand"
)
type Load struct {
val int
eod bool
}
type Worker struct {
name string
speed int
done int
}
func (w *Worker) Work(c chan Load, finished chan *Worker) {
for {
v := <-c
if v.eod {
fmt.Printf("finishing worker %v\n", w.name)
fmt.Printf("worker %v is done at %d\n", w.name, w.done)
finished <- w
} else {
fmt.Printf("worker %v got %d\n", w.name, v.val)
}
for i := 0; i < 10/w.speed; i++ {
time.Sleep(time.Millisecond * 1000)
}
fmt.Printf("worker %v processed %d\n", w.name, v.val)
w.done++
}
}
func main() {
c := make(chan Load)
finished := make(chan *Worker)
workers := []*Worker{
{name: "A", speed: 8},
{name: "B", speed: 2},
{name: "C", speed: 3},
}
// launch workers
for _, w := range workers {
go w.Work(c, finished)
}
// send loads
for i := 0; i < 30; i++ {
c <- Load{val: i, eod: false}
time.Sleep(time.Millisecond * time.Duration(rand.Int31n(2000)))
}
// send sentinels
for _, _ = range workers {
c <- Load{val: -1, eod: true}
}
remaining := make(map[*Worker]bool)
for _, w := range workers {
remaining[w] = false
}
for len(remaining) > 0 {
w := <-finished
delete(remaining, w)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment