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

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

http.TimeoutHandler 不會殺死相應(yīng)的 ServeHTTP goroutine

http.TimeoutHandler 不會殺死相應(yīng)的 ServeHTTP goroutine

Go
犯罪嫌疑人X 2023-06-26 17:39:20
超時處理程序?qū)?ServeHTTP 執(zhí)行轉(zhuǎn)移到新的 goroutine 上,但在計時器結(jié)束后無法終止該 goroutine。對于每個請求,它都會創(chuàng)建兩個 goroutine,但 ServeHTTP goroutine 永遠(yuǎn)不會用上下文殺死。無法找到殺死 goroutine 的方法。使用 time.Sleep 函數(shù)編輯For-loop,代表著巨大的計算量,超出了我們的計時器范圍。可以用任何其他功能替換它。package mainimport (    "fmt"    "io"    "net/http"    "runtime"    "time")type api struct{}func (a api) ServeHTTP(w http.ResponseWriter, req *http.Request) {    // For-loop block represents huge computation and usually takes more time    // Can replace with any code    i := 0    for {        if i == 500 {            break        }        fmt.Printf("#goroutines: %d\n", runtime.NumGoroutine())        time.Sleep(1 * time.Second)        i++    }    _, _ = io.WriteString(w, "Hello World!")}func main() {    var a api    s := http.NewServeMux()    s.Handle("/", a)    h := http.TimeoutHandler(s, 1*time.Second, `Timeout`)    fmt.Printf("#goroutines: %d\n", runtime.NumGoroutine())    _ = http.ListenAndServe(":8080", h)}ServeHTTP goroutine 應(yīng)該與請求上下文一起終止,通常不會發(fā)生這種情況。
查看完整描述

2 回答

?
翻過高山走不出你

TA貢獻1875條經(jīng)驗 獲得超3個贊

使用context.Context指示 go 例程中止其功能。當(dāng)然,Go 例程必須偵聽此類取消事件。

因此,對于您的代碼,請執(zhí)行以下操作:

ctx := req.Context() // this will be implicitly canceled by your TimeoutHandler after 1s


i := 0

for {

? ? if i == 500 {

? ? ? ? break

? ? }


? ? // for any long wait (1s etc.) always check the state of your context

? ? select {

? ? case <-time.After(1 * time.Second): // no cancelation, so keep going

? ? case <-ctx.Done():

? ? ? ? fmt.Println("request context has been canceled:", ctx.Err())

? ? ? ? return // terminates go-routine

? ? }

? ? i++

}


注意:?Context被設(shè)計為鏈?zhǔn)降?- 允許以級聯(lián)方式取消多個級別的子任務(wù)。

在典型的 REST 調(diào)用中,我們會發(fā)起數(shù)據(jù)庫請求。因此,為了確保此類阻塞和/或緩慢的調(diào)用及時完成,不應(yīng)使用Query?,而應(yīng)使用QueryContext?- 將 http 請求的上下文作為第一個參數(shù)傳遞。


查看完整回答
反對 回復(fù) 2023-06-26
?
幕布斯7119047

TA貢獻1794條經(jīng)驗 獲得超8個贊

我發(fā)現(xiàn),如果你沒有任何方法到達你的頻道,那么當(dāng) goroutine 運行時就沒有辦法殺死或停止它。

在大型計算任務(wù)中,您必須在特定時間間隔或特定任務(wù)完成后觀看通道。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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