我試圖重現“良好管理資源的方法是啟動固定數量的句柄 goroutines,所有這些 goroutines 都從請求通道讀取?!?從Effective Go 中發現fatal error: all goroutines are asleep - deadlock!這個想法很簡單:有 1 個隊列和 1 個結果通道和幾個有限數量的“工人”。我的代碼在 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功能服務: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.}怎么了?或者可能有更簡單的解決方案來實現數量有限的處理請求的工人?
- 1 回答
- 0 關注
- 202 瀏覽
添加回答
舉報
0/150
提交
取消