"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can Go\'s `context` Package Be Used to Timeout Goroutines?

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

Published on 2025-01-12
Browse:180

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

How Does Go Handle Timing Out Goroutines?

Question:

You are building a tool that handles multiple HTTP calls in concurrent goroutines. To prevent an indefinite execution scenario, you seek a way to cancel the goroutines after a specific time lapse.

Solution:

While the approach of creating a goroutine to sleep for a specified duration and sending a broadcast message to cancel the other goroutines seems logical, there seems to be an issue with the execution of goroutines in this scenario.

To address this challenge, consider leveraging the context package in Go. It offers an effective way to handle timeouts and context cancellation for goroutines.

Code Snippet:

Here's an example using the context package for timeout management of goroutines:

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()
}

This code creates a context with a 50-millisecond timeout. A goroutine is then launched to execute the test function, passing the context. Within the test function, a select statement waits for either the timeout to occur or the context to be cancelled. After 30 milliseconds, the context is cancelled, causing the goroutine to finish and print "cancelled."

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3