我試圖重現(xiàn)“良好管理資源的方法是啟動(dòng)固定數(shù)量的句柄 goroutines,所有這些 goroutines 都從請(qǐng)求通道讀取。” 從Effective Go 中發(fā)現(xiàn)fatal error: all goroutines are asleep - deadlock!這個(gè)想法很簡單:有 1 個(gè)隊(duì)列和 1 個(gè)結(jié)果通道和幾個(gè)有限數(shù)量的“工人”。我的代碼在 Go Playgroundqueue := 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功能服務(wù):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.}怎么了?或者可能有更簡單的解決方案來實(shí)現(xiàn)數(shù)量有限的處理請(qǐng)求的工人?
- 1 回答
- 0 關(guān)注
- 198 瀏覽
添加回答
舉報(bào)
0/150
提交
取消