Home >Backend Development >Golang >How Can Go\'s `context` Package Be Used to Timeout Goroutines?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-20 04:36:02825browse

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."

The above is the detailed content of How Can Go's `context` Package Be Used to Timeout Goroutines?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn