Home >Backend Development >Golang >How to Gracefully Stop Goroutines After a Set Time Using Context?
In load testing, where numerous HTTP calls are orchestrated in goroutines, it becomes crucial to control the execution duration of these routines. This allows users to terminate the load test at a predefined time.
One common attempt at achieving this is to employ goroutines to monitor time.Sleep() durations and broadcast termination signals via channels. While this method may suffice in certain cases, it fails when goroutines continue making HTTP calls outside the main goroutine.
Go 1.7 introduces the essential context package to address this issue. Contexts provide a structured way to cancel and monitor goroutine execution, offering a reliable solution for time-based termination.
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) }
Explanation:
This approach ensures that goroutines are canceled when the specified time has passed, regardless of their location in the code.
The above is the detailed content of How to Gracefully Stop Goroutines After a Set Time Using Context?. For more information, please follow other related articles on the PHP Chinese website!