【发布时间】:2020-12-10 21:16:53
【问题描述】:
Effective Go 指南有以下处理客户端请求的示例:
func handle(queue chan *Request) {
for r := range queue {
process(r)
}
}
func Serve(clientRequests chan *Request, quit chan bool) {
// Start handlers
for i := 0; i < MaxOutstanding; i++ {
go handle(clientRequests)
}
<-quit // Wait to be told to exit.
}
我在本地运行了类似的代码,其中客户端请求只是整数:
func handle(queue chan int) {
for r := range queue {
fmt.Println("r = ", r)
}
}
func serve(clientRequests chan int, quit chan bool) {
// Start handlers
for i := 0; i < 10; i++ {
go handle(clientRequests)
}
<-quit // Wait to be told to exit.
}
var serveChannel = make(chan int)
var quit = make(chan bool)
serve(serveChannel, quit)
for i := 0; i < 10; i++ {
serveChannel <- i
}
但是我的代码导致死锁错误fatal error: all goroutines are asleep - deadlock!。
即使我从概念上不了解程序中的问题,我也不了解原始代码的工作原理。我确实知道MaxOutstanding goroutines 已生成,它们都收听单个clientRequests 频道。但是clientRequests 通道只针对一个请求,所以一旦有请求进来,所有的 goroutine 都可以访问同一个请求。为什么这有用?
【问题讨论】:
标签: go concurrency deadlock goroutine