From 0fbbc70ba5dc7a1a900f527f90da96d63da481dc Mon Sep 17 00:00:00 2001 From: Richard Morrison Date: Mon, 28 Oct 2019 09:01:20 +0000 Subject: [PATCH] Remove magic numbers from code --- examples/worker-pools/worker-pools.go | 9 +++++---- examples/worker-pools/worker-pools.hash | 4 ++-- public/worker-pools | 13 +++++++------ 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/examples/worker-pools/worker-pools.go b/examples/worker-pools/worker-pools.go index 1584d59..b3c8892 100644 --- a/examples/worker-pools/worker-pools.go +++ b/examples/worker-pools/worker-pools.go @@ -27,8 +27,9 @@ func main() { // In order to use our pool of workers we need to send // them work and collect their results. We make 2 // channels for this. - jobs := make(chan int, 100) - results := make(chan int, 100) + const numJobs = 5 + jobs := make(chan int, numJobs) + results := make(chan int, numJobs) // This starts up 3 workers, initially blocked // because there are no jobs yet. @@ -38,7 +39,7 @@ func main() { // Here we send 5 `jobs` and then `close` that // channel to indicate that's all the work we have. - for j := 1; j <= 5; j++ { + for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) @@ -47,7 +48,7 @@ func main() { // This also ensures that the worker goroutines have // finished. An alternative way to wait for multiple // goroutines is to use a [WaitGroup](waitgroups). - for a := 1; a <= 5; a++ { + for a := 1; a <= numJobs; a++ { <-results } } diff --git a/examples/worker-pools/worker-pools.hash b/examples/worker-pools/worker-pools.hash index 97b94fd..4f1f158 100644 --- a/examples/worker-pools/worker-pools.hash +++ b/examples/worker-pools/worker-pools.hash @@ -1,2 +1,2 @@ -dbe5adf9aad6828387231e477e22c5f0cd550b74 -WXYS5_KpNvq +f6fd187061dfd0ae5ae8243efa3a6fcfa0777c84 +hiSJJsYZJKL diff --git a/public/worker-pools b/public/worker-pools index 97ea215..0b7c7d1 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -42,7 +42,7 @@ a worker pool using goroutines and channels.

- +
package main
 
@@ -109,8 +109,9 @@ channels for this.

-
    jobs := make(chan int, 100)
-    results := make(chan int, 100)
+          
    const numJobs = 5
+    jobs := make(chan int, numJobs)
+    results := make(chan int, numJobs)
 
@@ -140,7 +141,7 @@ channel to indicate that’s all the work we have.

-
    for j := 1; j <= 5; j++ {
+          
    for j := 1; j <= numJobs; j++ {
         jobs <- j
     }
     close(jobs)
@@ -159,7 +160,7 @@ goroutines is to use a WaitGroup.

-
    for a := 1; a <= 5; a++ {
+          
    for a := 1; a <= numJobs; a++ {
         <-results
     }
 }
@@ -223,7 +224,7 @@ there are 3 workers operating concurrently.