type Pool []*Worker
func (p Pool) Len() int { return len(p) }
-func (p Pool) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+func (p Pool) Swap(i, j int) {
+ p[i], p[j] = p[j], p[i]
+ p[i].index = i
+ p[j].index = j
+}
// FIXME: Does it works correctly? Or i need p[i] > p[j] ? The highest-pri
// worker should be the last.
func (p Pool) Less(i, j int) bool {
}
func (w worker) String() string {
- return fmt.Sprintf("W %.2d (%v)", w.num, w.pending)
+ return fmt.Sprintf("W %.2d (%v [%v])", w.num, w.pending, w.index)
}
// Done message is sent by work runner to balancer, when request is completed.
type pool []*worker
func (p pool) Len() int { return len(p) }
-func (p pool) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+func (p pool) Swap(i, j int) {
+ p[i], p[j] = p[j], p[i]
+ p[i].index = i
+ p[j].index = j
+}
func (p pool) Less(i, j int) bool {
return p[i].pending < p[j].pending
}
// dispatch sends requests to least loaded worker.
func (b *Balancer) dispatch(req Requester) {
w := heap.Pop(&b.pool).(*worker)
- fmt.Printf("dispatch() '%v': sending to '%v'\n", req, w)
w.pending++
heap.Push(&b.pool, w)
+ fmt.Printf("dispatch() '%v': sending to '%v'\n", req, w)
w.runner.Send(req)
- fmt.Printf("dispatch() '%v': sent\n", req)
+ fmt.Printf("dispatch() '%v': sent to %v\n", req, w)
}
// completed re-inserts worker, which finished request, into proper place in the pool.
w.pending--
heap.Remove(&b.pool, w.index)
heap.Push(&b.pool, w)
+ fmt.Println("pool", b.pool)
}
// InitBalancer initializes balancer with provided workers.
case req := <- w.Requests:
fmt.Printf(" %v [%v]: start computing '%v'\n", w, id, req)
req.Send(req.Fn())
- done <- &balancer.Done{w.id, req}
fmt.Printf(" %v [%v]: finished '%v'\n", w, id, req)
+ done <- &balancer.Done{w.id, req}
+ fmt.Printf(" %v [%v]: done '%v'\n", w, id, req)
case <-timeout:
fmt.Printf(" %v [%v]: i'm still here..\n", w.id, id)
timeout = time.After(time.Second)