第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 Done 通道和未關(guān)閉通道的 GC 生成 context.Context

從 Done 通道和未關(guān)閉通道的 GC 生成 context.Context

Go
慕容708150 2023-07-26 19:31:21
背景:我正在利用自定義 LDAP 服務(wù)器包。它使用Done請求中的通道讓處理程序知道是否(例如客戶端斷開連接),因此處理程序也應(yīng)該中止。由于Done通道是處理取消的舊方法 - 并且我希望支持取消鏈接 - 我context.Context從這個通道創(chuàng)建了一個,如下所示:func doneContext(p context.Context, done <-chan bool) (? ? ctx context.Context, cancel context.CancelFunc,) {? ? ctx, cancel = context.WithCancel(p)? ? go func() {? ? ? ? ? ? <-done? ? ? ? ? ? cancel() // done closed, so cancel our context? ? }()? ? return}這假設(shè)done通道將關(guān)閉:客戶端斷開連接;和成功的處理程序(完全運(yùn)行完成)第一個事實證明是正確的,而第二個事實則不然。成功的處理程序調(diào)用不會觸發(fā)通道done關(guān)閉 - 因此我泄漏了 go-routines。為了解決這個問題 - 由于我context.Context在處理程序完成時取消了自己的操作 - 成功與否,例如// convert the client request's Done channel into a context.Contextctx, cancel := doneContext(context.Background(), m.Done)defer cancel() // clean-up context: rain or shine我doneContext像這樣更新了 go 例程:go func() {? ? ? ? select {? ? ? ? case <-done:? ? ? ? ? ? cancel() // done closed, so cancel our context (like before)? ? ? ? case <-ctx.Done():? ? ? ? ? ? // when our context is canceled, recover the go-routine (even if done never closes)? ? ? ? }}()問題:這是將舊式done頻道升級為更現(xiàn)代頻道的正確方法嗎context.Context我應(yīng)該擔(dān)心我正在使用的外部包沒有關(guān)閉通道嗎done?即會GC收集該通道,即使它從未關(guān)閉?
查看完整描述

1 回答

?
有只小跳蛙

TA貢獻(xiàn)1824條經(jīng)驗 獲得超8個贊

您不需要關(guān)閉頻道。如果沒有任何內(nèi)容引用該通道,它將被垃圾收集。

您的頻道邏輯看起來是正確的。


查看完整回答
反對 回復(fù) 2023-07-26
  • 1 回答
  • 0 關(guān)注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號