有兩種不同的方法來清理 goroutine。使用 kill channel 表示取消,使用 done channel 表示 goroutine 已經(jīng)終止。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()每種方法的優(yōu)點/缺點是什么?我應(yīng)該默認(rèn)哪一個?我知道如果我想殺死一棵相互連接的 goroutines 樹,我應(yīng)該使用上下文方法,但我們只是說我有一個簡單的 worker,它不會在內(nèi)部啟動其他 goroutines。
1 回答

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