3 回答

TA貢獻1887條經驗 獲得超5個贊
兩種方式的成本都非常低。goroutines 不需要單獨的操作系統線程,并且在阻塞通道接收時幾乎不消耗資源,但啟動的成本也很低,因此也沒有充分的理由讓它們保持打開狀態。
我的代碼很少使用工作池。通常,我的生產者會為其生成的每個工作單元生成一個 goroutine,并將其與響應通道一起直接傳遞出去,然后生成一個“偵聽器”,它對工作輸出進行一些格式化并將所有響應通過管道返回到主線程。我的常見模式如下:
func Foo(input []interface{}) resp chan interface{} {
var wg sync.WaitGroup
resp := make(chan interface{})
listen := make(chan interface{})
theWork := makeWork(input)
// do work
for _, unitOfWork := range theWork {
wg.Add(1)
go func() {
// doWork has signature:
// func doWork(w interface{}, ch chan interface{})
doWork(unitOfWork, listen)
wg.Done()
}()
}
// format the output of listen chan and send to resp chan
// then close resp chan so main can continue
go func() {
for r := range listen {
resp <- doFormatting(r)
}
close(resp)
}()
// close listen chan after work is done
go func() {
wg.Wait()
close(listen)
}()
return resp
}
然后我的主函數將一些輸入傳遞給它并監聽響應通道
func main() {
loremipsum := []string{"foo", "bar", "spam", "eggs"}
response := Foo(loremipsum)
for output := range response {
fmt.Println(output)
}
}

TA貢獻1796條經驗 獲得超4個贊
任務隊列和等待工人的模式在 Go 中很常見。Goroutines 很便宜,但執行順序是不確定的。因此,如果您希望您的系統行為是可預測的,您最好通過循環或其他方式請求的無緩沖通道控制工作人員與主程序的會合。否則,其中一些可以生成但保持空閑狀態,這是合法的。
- 3 回答
- 0 關注
- 199 瀏覽
添加回答
舉報