在这个例子中,我们将看看如何使用goroutines
和channel
实现一个工作池。
这里是工作程序(worker
),我们将运行几个并发实例。这些工作程序(worker
)将在工作渠道上接收工作,并将结果发送相应的结果。将每个工作程序(worker
)睡一秒钟,用来模拟执行的任务。
为了使用工作程序(worker
)池,需要向它们发送工作(或作业)并收集的结果。为此做2
个通道。
这启动了3
个工作程序(worker
),最初被阻止,因为还没有作业。
然后,我们再发送5
个作业,然后关闭该通道,以指示这是所有的工作。
最后,收集作业的所有结果。
运行程序显示了5
个作业正在由各种工作程序执行。该程序只需要约2
秒的时间,尽管做了大约5
秒的总工作,因为有3
个工作程序同时操作。
所有的示例代码,都放在
F:\worksp\golang
目录下。安装Go编程环境请参考:http://www.yiibai.com/go/go_environment.html
timers.go
的完整代码如下所示 -
package main
import "fmt"
import "time"
// Here's the worker, of which we'll run several
// concurrent instances. These workers will receive
// work on the `jobs` channel and send the corresponding
// results on `results`. We'll sleep a second per job to
// simulate an expensive task.
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
results <- j * 2
}
}
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)
// This starts up 3 workers, initially blocked
// because there are no jobs yet.
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// 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++ {
jobs <- j
}
close(jobs)
// Finally we collect all the results of the work.
for a := 1; a <= 5; a++ {
<-results
}
}
执行上面代码,将得到以下输出结果 -
F:\worksp\golang>go run worker-pools.go
worker 3 started job 2
worker 1 started job 1
worker 2 started job 3
worker 3 finished job 2
worker 3 started job 4
worker 1 finished job 1
worker 1 started job 5
worker 2 finished job 3
worker 3 finished job 4
worker 1 finished job 5