From d5394c935ab878013c8c53298e365e4fddadbe48 Mon Sep 17 00:00:00 2001 From: sgf Date: Wed, 26 Oct 2022 21:19:16 +0300 Subject: [PATCH] chg(balancer): work() function instance identification. This shows bug in existing (my) code: dispatch() starts new worker (w.work()) for every call, resulting in many workers, instead of one per 'Worker' structure in a Pool. --- concurrency-is-not-parallelism/balancer.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/concurrency-is-not-parallelism/balancer.go b/concurrency-is-not-parallelism/balancer.go index cea7ea8..1d17729 100644 --- a/concurrency-is-not-parallelism/balancer.go +++ b/concurrency-is-not-parallelism/balancer.go @@ -66,16 +66,22 @@ func (w Worker) String() string { return fmt.Sprintf("W %.2d (%v)", w.num, w.pending) } -func (w *Worker) work(done chan<- *Done) { +func (w *Worker) work(id string, done chan<- *Done) { t := rand.Intn(5) - fmt.Printf("%v: sleeping for %v secs before begin..\n", w, t) + fmt.Printf(" %v [%v]: sleeping for %v secs before begin..\n", w, id, t) time.Sleep(time.Duration(t) * time.Second) + timeout := time.After(time.Second) for { - req := <- w.requests - fmt.Printf("%v: start computing '%v'\n", w, req) - req.c <- req.fn() - done <- &Done{w, req} - fmt.Printf("%v: finished '%v'\n", w, req) + select { + case req := <- w.requests: + fmt.Printf(" %v [%v]: start computing '%v'\n", w, id, req) + req.c <- req.fn() + done <- &Done{w, req} + fmt.Printf(" %v [%v]: finished '%v'\n", w, id, req) + case <-timeout: + fmt.Printf(" %v [%v]: i'm stil here..\n", w, id) + timeout = time.After(time.Second) + } } } @@ -135,7 +141,7 @@ out: func (b *Balancer) dispatch(req *Request) { w := heap.Pop(&b.pool).(*Worker) fmt.Printf("dispatch() '%v': sending to '%v'\n", req, w) - go w.work(b.done) + go w.work(time.Now().Format("05.000"), b.done) w.pending++ heap.Push(&b.pool, w) w.requests <- req -- 2.20.1