有兩種不同的方法來清理 goroutine。使用 kill channel 表示取消,使用 done channel 表示 goroutine 已經終止。type Worker struct { Done chan struct{} Kill chan struct{} Jobs chan Job}func (w *Worker) Run() { defer func() { w.Done <- struct{}{} } for { select { case <-w.Kill: return case j := <-w.Jobs: // Do some work }}go w.Run()w.Kill <- struct{}{}用于context取消type Worker struct { Ctx context.Context Cancel context.CancelFunc Jobs chan Job}func (w *Worker) Run() { for { select { case <-w.Ctx.Done(): return case j := <-w.Jobs: // Do some work }}go w.Run()w.Cancel()每種方法的優點/缺點是什么?我應該默認哪一個?我知道如果我想殺死一棵相互連接的 goroutines 樹,我應該使用上下文方法,但我們只是說我有一個簡單的 worker,它不會在內部啟動其他 goroutines。
1 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
Go 1.7 發行說明
語境
Go 1.7 將 golang.org/x/net/context 包作為上下文移入標準庫。這允許在其他標準庫包(包括 net、net/http 和 os/exec)中使用上下文來取消、超時和傳遞請求范圍的數據,如下所述。
有問題。引入上下文包來解決它們。
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消