// In this example we'll look at how to implement
// a _worker pool_ using goroutines and channels.
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
}
}
Go worker pool
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Go-ethereum 源码解析之 miner/worker.go (上) Source Code Appendi...
- Go-ethereum 源码解析之 miner/worker.go (下) Appendix D. 详细批注 1....
- 好的東西一起分享 包括一張圖片 我也不知道這是第幾張了 類似的話說了幾次 但我知道明天還有最後一張 哈哈 ...
- 原创申明:本文参加“423简书故事节”,本人承诺文章内容为原。 我本来只是一颗忠诚勇敢的小精子,亿万大军中的一员,...
- 近日台湾花莲发生6.5级大地震,伤亡惨重。而国人念兹在兹萦绕心头的汶川大地震为里氏震级8.0级,您知道这两个地震能...