Home >Backend Development >Golang >How to Gracefully Stop Goroutines After a Set Time Using Context?

How to Gracefully Stop Goroutines After a Set Time Using Context?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 14:48:18833browse

How to Gracefully Stop Goroutines After a Set Time Using Context?

How to Halt Goroutines after Specified Duration Using Context

Problem Background

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.

A Failed Approach

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.

The Solution: Using Contexts

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:

  1. Inside the test function, a context with a 50 millisecond timeout is created.
  2. A select statement checks if the time.After channel has an event (indicating sleep completion) or if the context has been canceled.
  3. When the context times out, the select statement exits, indicating that the goroutine has been canceled.

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!

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