在這個例子中,我們將看看如何使用goroutines
和channel
實現一個工作池。
這裡是工作程式(worker
),我們將執行幾個並行範例。這些工作程式(worker
)將在工作渠道上接收工作,並將結果傳送相應的結果。將每個工作程式(worker
)睡一秒鐘,用來模擬執行的任務。
為了使用工作程式(worker
)池,需要向它們傳送工作(或作業)並收集的結果。為此做2
個通道。
這啟動了3
個工作程式(worker
),最初被阻止,因為還沒有作業。
然後,我們再傳送5
個作業,然後關閉該通道,以指示這是所有的工作。
最後,收集作業的所有結果。
執行程式顯示了5
個作業正在由各種工作程式執行。該程式只需要約2
秒的時間,儘管做了大約5
秒的總工作,因為有3
個工作程式同時操作。
所有的範例程式碼,都放在
F:\worksp\golang
目錄下。安裝Go程式設計環境請參考:/2/23/798.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