Home > Backend Development > Golang > How to Gracefully Timeout Goroutines in Go?

How to Gracefully Timeout Goroutines in Go?

Patricia Arquette
Release: 2024-11-19 11:56:02
Original
1040 people have browsed it

How to Gracefully Timeout Goroutines in Go?

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)
}
Copy after login

In this code:

  • A context.Context is created with a timeout of 50 milliseconds using context.WithTimeout().
  • The test() goroutine runs in this context and awaits instructions via select.
  • After the timeout elapses, select receives the ctx.Done() signal and exits the goroutine gracefully, preventing oversleep.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template