chg(balancer): work() function instance identification.
authorsgf <sgf.dma@gmail.com>
Wed, 26 Oct 2022 18:19:16 +0000 (21:19 +0300)
committersgf <sgf.dma@gmail.com>
Wed, 26 Oct 2022 18:19:16 +0000 (21:19 +0300)
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

index cea7ea8..1d17729 100644 (file)
@@ -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