How to Timeout Goroutines in Go to Control Execution Time
Goroutines, an integral part of Go concurrency, allow for asynchronous execution of tasks. However, sometimes, it's necessary to control the duration of these routines and prevent them from executing indefinitely.
Background and Problem
In your load testing tool, you want to terminate goroutines after a specified time to limit the duration of the HTTP call process. The current approach using time.Sleep() within a goroutine creates a channel for communication, but it results in premature termination of goroutines.
Solution using Context
A more recommended approach involves utilizing the golang.org/x/net/context package (available in the standard library in Go 1.7 ), specifically the context.Context interface. Context provides a mechanism for canceling or timing out goroutines.
The following code snippet demonstrates this solution:
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("used:", time.Since(t)) } func main() { ctx, _ := context.WithTimeout(context.Background(), 50*time.Millisecond) test(ctx) }
In this code:
The above is the detailed content of How to Gracefully Timeout Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!