同步示例:
type job struct {
Id int
Message string
}
for {
// getJob() blocks until job is received
job := getJob()
doSomethingWithJob(job)
}
doSomethingWithJobgetJob
doSomethingWithJobgetJob
go routines 的概念目前让我感到困惑,因此非常感谢任何指向正确方向的指针来帮助我学习。
更新:感谢@JimB 的帮助。为什么 worker 5 总是接手工作?
jobCh := make(chan *job)
// Max 5 Workers
for i := 0; i < 5; i++ {
go func() {
for job := range jobCh {
time.Sleep(time.Second * time.Duration(rand.Intn(3)))
log.Println(i, string(job.Message))
}
}()
}
for {
job, err := getJob()
if err != nil {
log.Println("Closing Channel")
close(jobCh)
break
}
jobCh <- job
}
log.Println("Complete")
示例输出
2016/06/09 22:19:57 5 {"id":10692,"name":"Test Message"}
2016/06/09 22:19:57 5 {"id":10687,"name":"Test Message"}
2016/06/09 22:19:57 5 {"id":10699,"name":"Test Message"}
2016/06/09 22:19:57 5 {"id":10701,"name":"Test Message"}
2016/06/09 22:19:57 5 {"id":10703,"name":"Test Message"}
2016/06/09 22:19:57 5 {"id":10704,"name":"Test Message"}