chg(balancer): Use more pointers to avoid copying data.
authorsgf <sgf.dma@gmail.com>
Wed, 26 Oct 2022 17:40:39 +0000 (20:40 +0300)
committersgf <sgf.dma@gmail.com>
Wed, 26 Oct 2022 17:40:39 +0000 (20:40 +0300)
concurrency-is-not-parallelism/balancer.go

index 2cae58c..d39d69e 100644 (file)
@@ -18,12 +18,12 @@ func (r Request) String() string {
     return fmt.Sprintf("R %.2d", r.num)
 }
 
-func workFn(r Request) int {
+func workFn(r *Request) int {
     fmt.Printf("%v: computing (workFn).. (%p)\n", r, r.fn)
     return r.num
 }
 
-func furtherProcess(r Request, result int) {
+func furtherProcess(r *Request, result int) {
     fmt.Printf("%v: further processing result %v..\n", r, result)
 }
 
@@ -36,13 +36,13 @@ func requester(work chan<- Request) {
         time.Sleep(time.Duration(t) * time.Second)
 
         req := &Request{num: reqNum, c: c}
-        fn := func () int { return workFn(*req) }
+        fn := func () int { return workFn(req) }
         req.fn = fn
         fmt.Printf("requester() '%v': sending\n", req)
         work <- *req
         result := <-c
         fmt.Printf("requester() '%v': received result %v\n", req, result)
-        furtherProcess(*req, result)
+        furtherProcess(req, result)
         reqNum++
     }
 }
@@ -59,7 +59,7 @@ type Worker struct {
 
 type Done struct {
     w *Worker
-    r Request
+    r *Request
 }
 
 func (w Worker) String() string {
@@ -74,7 +74,7 @@ func (w *Worker) work(done chan<- *Done) {
         req := <- w.requests
         fmt.Printf("%v: start computing '%v'\n", w, req)
         req.c <- req.fn()
-        done <- &Done{w, req}
+        done <- &Done{w, &req}
         fmt.Printf("%v: finished '%v'\n", w, req)
     }
 }
@@ -143,8 +143,8 @@ func (b *Balancer) dispatch(req Request) {
 }
 
 func (b *Balancer) completed(done *Done) {
-    done.w.pending--
     fmt.Printf("completed() '%v': finished '%v'\n", done.w, done.r)
+    done.w.pending--
     heap.Remove(&b.pool, done.w.index)
     heap.Push(&b.pool, done.w)
 }