Home >Backend Development >Golang >How to Stop a Go Goroutine Execution After a Timeout?

How to Stop a Go Goroutine Execution After a Timeout?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 11:21:15185browse

How to Stop a Go Goroutine Execution After a Timeout?

Stopping Goroutine Execution on Timeout

In Go, goroutines provide a lightweight way to execute code concurrently. However, sometimes it's necessary to stop a goroutine after a specific amount of time.

Problem:

A user encountered an issue where a goroutine continued executing even after a timeout was set. They expected the goroutine to stop immediately upon reaching the timeout, but instead, it printed additional messages. Here's an example code:

type Response struct {
    data   interface{}
    status bool
}

func Find() (interface{}, bool) {
    ch := make(chan Response, 1)

    go func() {
        time.Sleep(10 * time.Second)
        fmt.Println("test")
        fmt.Println("test1")
        ch <- Response{data: "data", status: true}
    }()

    select {
    case <-ch:
        fmt.Println("Read from ch")
        res := <-ch
        return res.data, res.status
    case <-time.After(50 * time.Millisecond):
        return "Timed out", false
    }
}

Expected Output:

  • Timed out

Actual Output:

  • Timed out
  • test
  • test1

Analysis:

The problem arises because the timeout is set on the receiving end of the channel ch, not on the sending end. While the timeout correctly identifies that no data was received within 50 milliseconds, it doesn't prevent the goroutine from executing further and sending data on the channel afterwards.

Solution:

Since it's not possible to directly interrupt a goroutine's execution in Go, alternative approaches are needed:

  • Use unbuffered channels, which block sending and force the goroutine to wait until the channel is ready to receive.
  • Use context with cancellation and pass it into the goroutine. When the timeout occurs, cancel the context, and the goroutine should check the context and return early.
  • Use a custom synchronization technique, such as a mutex or waitgroup, to control goroutine execution and ensure timely termination.

The above is the detailed content of How to Stop a Go Goroutine Execution After a Timeout?. 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