翻译自 https://gobyexample.com/
Go by Example
Go is an open source programming language designed for building simple, fast, and reliable software.
Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.
Go by Example: Worker Pools
这节探索如何使用goroutine
和channel
实现工作池的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package main
import "fmt" import "time"
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() { jobs := make(chan int, 100) results := make(chan int, 100)
for w:= 1; w <= 3; w++ { go worker(w, jobs, results) }
for j:= 1; j <= 5; j++ { jobs <- j } close(jobs)
for a := 1; a <= 5; a++ { <-results } }
|
1 2 3 4 5 6 7 8 9 10 11
| tashuo:golang ta_shuo$ go run worker-pool.go worker 3 started job 1 worker 2 started job 3 worker 1 started job 2 worker 3 finished job 1 worker 3 started job 4 worker 2 finished job 3 worker 1 finished job 2 worker 2 started job 5 worker 2 finished job 5 worker 3 finished job 4
|
通过输出可以看出5个任务被多个工作进程执行。程序只消耗了2秒多而不是5秒,是因为所有的任务被3个工作进程并发处理。
原文链接:Go by Example: Worker Pools