type job struct {
Id int
Message string
}
for {
// getJob() blocks until job is received
job := getJob()
doSomethingWithJob(job)
}
getJobdoSomethingWithJob
getJobdoSomethingWithJob
go例程的概念目前让我困惑,所以任何指向正确方向的指针都会非常感谢,以帮助我学习。
更新:谢谢@JimB的帮助。为什么工人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"}
2016-06-09 Gravy
+0
它不是第5个工人,每个工人都有i = 5。它应该是'去func(我int){...}(i)'https://golang.org/doc/faq#closures_and_goroutines –