先啓動固定數量的goroutine,每一個goroutine都在從channel中獲取數據,若是這個channel爲空,就阻塞等待在那裏
channel中傳遞一個Car類型,這個類型主要負責具體作的任務
也就是channel就是運輸通道,在這個通道上傳遞Car這樣一個汽車,來一輛車就處理這輛車的工做,沒有車過來那這些工人就在那等着spa
package main import ( "log" "sync" "time" ) type Pool struct { workerNum int road chan *Car wg sync.WaitGroup } //初始化這個對象 func NewPool(wn int) *Pool { return &Pool{workerNum: wn, road: make(chan *Car)} } //往channel添加具體任務 func (p *Pool) AddCar(f *Car) { p.road <- f } //goroutine去工做 func (p *Pool) work(workId int) { for f := range p.road { log.Println("workId:", workId, "start") f.do() log.Println("workId:", workId, "done") } p.wg.Done() } //建立goroutine等着接工做 func (p *Pool) Run() { for i := 0; i < p.workerNum; i++ { go p.work(i) p.wg.Add(1) } p.wg.Wait() } func (p *Pool) colse() { close(p.road) } func main() { pool := NewPool(5) go func() { //模擬要作10件事 for i := 0; i < 10; i++ { car := Car{ param: i, } pool.AddCar(&car) } pool.colse() }() pool.Run() } /*具體作的事經過這個來傳遞*/ type Car struct { param int } func (c *Car) do() error { log.Println(time.Now(), c.param) return nil }