chg(balancer): Return pointer to request in request result.
authorsgf <sgf.dma@gmail.com>
Tue, 1 Nov 2022 17:01:18 +0000 (20:01 +0300)
committersgf <sgf.dma@gmail.com>
Tue, 1 Nov 2022 17:01:18 +0000 (20:01 +0300)
concurrency-is-not-parallelism/balancer_v2/balancer/requester/requester.go

index 593b98a..e414087 100644 (file)
@@ -8,10 +8,20 @@ import (
     "balancer"
 )
 
+// Anonymous struct fields, essentially struct emebedding.
+type reqResult struct {
+    *request
+    int
+}
+
+func (r reqResult) String() string {
+    return fmt.Sprintf("%v", r.int)
+}
+
 type request struct {
     reqFn func() int    // what to compute for this particular request.
     num int             // Used for request identification.
-    c chan int          // channel for obtaining results back from worker.
+    c chan reqResult    // channel for obtaining results back from worker.
 }
 
 func (r request) String() string {
@@ -22,19 +32,19 @@ var _ balancer.Requester = (*request)(nil)
 
 func (r *request) Fn() interface{} {
     fmt.Printf("%v: Fn()..\n", r)
-    return interface{}(r.reqFn())
+    return interface{}(reqResult{r, r.reqFn()})
 }
 
 func (r *request) Send(res interface{}) {
-    r.c <- res.(int)
+    r.c <- res.(reqResult)
 }
 
-func furtherProcess(r *request, result int) {
-    fmt.Printf("%v: further processing result %v..\n", r, result)
+func furtherProcess(r reqResult) {
+    fmt.Printf("%v: further processing result %v..\n", r.request, r.int)
 }
 
 func Generate(work chan<- balancer.Requester) {
-    c := make(chan int)
+    c := make(chan reqResult)
     reqNum := 0
     for {
         t := rand.Intn(5)
@@ -47,7 +57,7 @@ func Generate(work chan<- balancer.Requester) {
         work <- req
         result := <-c
         fmt.Printf("Generate() '%v': received result %v\n", req, result)
-        furtherProcess(req, result)
+        furtherProcess(result)
         reqNum++
     }
 }