」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Go 的 context 套件如何用於超時 Goroutine?

Go 的 context 套件如何用於超時 Goroutine?

發佈於2025-01-12
瀏覽:181

How Can Go\'s `context` Package Be Used to Timeout Goroutines?

Go 如何處理超時 Goroutine?

問題:

您正在建立一個處理多個 HTTP 呼叫的工具在並發 goroutine 中。為了防止無限期執行的情況,您尋求一種在特定時間間隔後取消 goroutine 的方法。

解決方案:

同時創建goroutine 休眠的方法在指定的持續時間內發送廣播訊息來取消其他goroutine 似乎是合乎邏輯的,但此中goroutine的執行似乎存在問題scene.

為了應對這一挑戰,請考慮利用Go 中的上下文套件。它提供了一種有效的方法來處理 goroutine 的超時和上下文取消。

程式碼片段:

下面是使用 context 套件進行 goroutine 逾時管理的範例:

package main

import (
    "context"
    "fmt"
    "time"
)

func test(ctx context.Context) {
    t := time.Now()

    select {
    case <-time.After(1 * time.Second):
        fmt.Println("overslept")
    case <-ctx.Done():
        fmt.Println("cancelled")
    }
    fmt.Println("used:", time.Since(t))
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)

    go test(ctx)

    // cancel context after 30 milliseconds
    time.Sleep(30 * time.Millisecond)
    cancel()
}

此程式碼建立一個逾時時間為 50 毫秒的上下文。然後啟動一個 goroutine 來執行測試函數,並傳遞上下文。在測試函數中,選擇語句等待逾時發生或上下文被取消。 30 毫秒後,上下文被取消,導致 goroutine 完成並列印“cancelled”。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3