diff --git a/examples/worker-pools/worker-pools.go b/examples/worker-pools/worker-pools.go index 1584d59..eabab85 100644 --- a/examples/worker-pools/worker-pools.go +++ b/examples/worker-pools/worker-pools.go @@ -26,9 +26,13 @@ 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) + // channels for this. We use buffered channels + // because we want the workers to block until they + // receive on the `jobs` channel, but want to be able + // to send to either channel without blocking. + 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 +42,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 +51,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 dbfeb88..fb85ebb 100644 --- a/examples/worker-pools/worker-pools.hash +++ b/examples/worker-pools/worker-pools.hash @@ -1,2 +1,2 @@ -9b30cdfc3f46d634c3b8671a7ae1551c133fb6e2 -IiKZ-nj-nKY +72be5c38dbcb94a7567baa43726a4c44cbd187ea +OsX4R3HlGXG diff --git a/public/worker-pools b/public/worker-pools index 70a6a0b..0901317 100644 --- a/public/worker-pools +++ b/public/worker-pools @@ -42,7 +42,7 @@ a worker pool using goroutines and channels.
package 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.
+channels for this. We use buffered channels +because we want the workers to block until they +receive on thejobs
channel, but want to be able
+to send to either channel without blocking.
jobs := make(chan int, 100)
- results := make(chan int, 100)
+ const numJobs = 5
+ jobs := make(chan int, numJobs)
+ results := make(chan int, numJobs)
for j := 1; j <= 5; j++ {
+ for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
@@ -159,7 +163,7 @@ goroutines is to use a WaitGroup.
for a := 1; a <= 5; a++ {
+ for a := 1; a <= numJobs; a++ {
<-results
}
}
@@ -223,7 +227,7 @@ there are 3 workers operating concurrently.