@@ -13,8 +13,9 @@ import "time"
|
||||
// simulate an expensive task.
|
||||
func worker(id int, jobs <-chan int, results chan<- int) {
|
||||
for j := range jobs {
|
||||
fmt.Println("worker", id, "processing job", j)
|
||||
fmt.Println("worker", id, "started job", j)
|
||||
time.Sleep(time.Second)
|
||||
fmt.Println("worker", id, "finished job", j)
|
||||
results <- j * 2
|
||||
}
|
||||
}
|
||||
@@ -33,15 +34,15 @@ func main() {
|
||||
go worker(w, jobs, results)
|
||||
}
|
||||
|
||||
// Here we send 9 `jobs` and then `close` that
|
||||
// Here we send 5 `jobs` and then `close` that
|
||||
// channel to indicate that's all the work we have.
|
||||
for j := 1; j <= 9; j++ {
|
||||
for j := 1; j <= 5; j++ {
|
||||
jobs <- j
|
||||
}
|
||||
close(jobs)
|
||||
|
||||
// Finally we collect all the results of the work.
|
||||
for a := 1; a <= 9; a++ {
|
||||
for a := 1; a <= 5; a++ {
|
||||
<-results
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
9d5b1d008d278df7db7697d56d491d982da86e7d
|
||||
y12QxBsKtT
|
||||
1f9acf1e50be05cad73e6b085ed3294892c67d42
|
||||
RTRcHA05vV
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
# Our running program shows the 9 jobs being executed by
|
||||
# various workers. The program only takes about 3 seconds
|
||||
# despite doing about 9 seconds of total work because
|
||||
# Our running program shows the 5 jobs being executed by
|
||||
# various workers. The program only takes about 2 seconds
|
||||
# despite doing about 5 seconds of total work because
|
||||
# there are 3 workers operating concurrently.
|
||||
$ time go run worker-pools.go
|
||||
worker 1 processing job 1
|
||||
worker 2 processing job 2
|
||||
worker 3 processing job 3
|
||||
worker 1 processing job 4
|
||||
worker 2 processing job 5
|
||||
worker 3 processing job 6
|
||||
worker 1 processing job 7
|
||||
worker 2 processing job 8
|
||||
worker 3 processing job 9
|
||||
worker 1 started job 1
|
||||
worker 2 started job 2
|
||||
worker 3 started job 3
|
||||
worker 1 finished job 1
|
||||
worker 1 started job 4
|
||||
worker 2 finished job 2
|
||||
worker 2 started job 5
|
||||
worker 3 finished job 3
|
||||
worker 1 finished job 4
|
||||
worker 2 finished job 5
|
||||
|
||||
real 0m3.149s
|
||||
real 0m2.358s
|
||||
|
||||
Reference in New Issue
Block a user