【发布时间】:2013-12-21 13:33:14
【问题描述】:
我试图重现“管理资源的方法是启动固定数量的句柄 goroutine,所有这些都从请求通道读取。”从Effective Go 发现
fatal error: all goroutines are asleep - deadlock!
这个想法很简单:有 1 个队列和 1 个结果通道以及几个有限数量的“工人”。
我的代码是in Go Playground
queue := make(chan *Request)
result := make(chan int)
quit := make(chan bool)
go Serve(queue, quit)
for i := 0; i < 10; i++ {
req := Request{i, result}
queue <- &req
}
close(queue)
for i := 0; i < 10; i++ {
fmt.Printf("Finished %d\n", <-result)
}
fmt.Printf("All finished\n")
quit <- true
功能服务:
func handle(queue chan *Request) {
for r := range queue {
//process(r)
fmt.Printf("Processing %d\n", r.i)
r.r <- r.i
}
}
func Serve(clientRequests chan *Request, quit chan bool) {
MaxOutstanding := 2
// Start handlers
for i := 0; i < MaxOutstanding; i++ {
go handle(clientRequests)
}
<-quit // Wait to be told to exit.
}
怎么了?或者可能有更简单的解决方案来实现处理请求的有限数量的工作人员?
【问题讨论】:
标签: go