使用goroutine和channel构建生产者消费者模型,指定启动的goroutine数量。
关键词:生产者消费者模型,golang
Go语言使用并发很方便,但是goroutine并不是越多越好。通常使用workpool模式,控制goroutine的数量,防止goroutine泄露和暴涨。
简易生产者模型
一个简易的生产者消费者模型代码如下:
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
| func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Printf("worker:%d start jobs:%d\n", id, j) time.Sleep(time.Second) fmt.Printf("worker:%d end jobs:%d\n", id, 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 } }
|