Home >Backend Development >Golang >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:
Actual Output:
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:
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!