在這個例子中,我們將看看如何使用goroutines和channel實現一個工作池。
這里是工作程序(worker),我們將運行幾個并發(fā)實例。這些工作程序(worker)將在工作渠道上接收工作,并將結果發(fā)送相應的結果。將每個工作程序(worker)睡一秒鐘,用來模擬執(zhí)行的任務。
為了使用工作程序(worker)池,需要向它們發(fā)送工作(或作業(yè))并收集的結果。為此做2個通道。
這啟動了3個工作程序(worker),最初被阻止,因為還沒有作業(yè)。
然后,我們再發(fā)送5個作業(yè),然后關閉該通道,以指示這是所有的工作。
最后,收集作業(yè)的所有結果。
運行程序顯示了5個作業(yè)正在由各種工作程序執(zhí)行。該程序只需要約2秒的時間,盡管做了大約5秒的總工作,因為有3個工作程序同時操作。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請參考: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
}
}
執(zhí)行上面代碼,將得到以下輸出結果 -
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