Cancelling Goroutine Execution on Timeout
In Go routines, it may be necessary to terminate operations beyond a specific time threshold. This can present challenges, as Go typically runs goroutines asynchronously without direct control over their execution. One common scenario arises when using the iris framework, where you may encounter situations where a goroutine continues execution even after a timeout has occurred.
Consider the following code snippet:
package main import ( "fmt" "time" ) func main() { Res := make(chan Response, 1) go func() { time.Sleep(10 * time.Second) fmt.Println("test") Res <- Response{data: "data", status: true} }() select { case <-Res: fmt.Println("Read from ch") res := <-Res fmt.Println(res.data, res.status) case <-time.After(50 * time.Millisecond): fmt.Println("Timed out") } } type Response struct { data interface{} status bool }
As illustrated in the example, a goroutine is launched to print test after a 10-second delay. A channel (Res) is used to facilitate communication between the goroutine and the main goroutine. A select statement is employed to wait for either a response from the goroutine or a timeout of 50 milliseconds.
However, the expected behavior is that the goroutine should be terminated as soon as the timeout occurs. Instead, the output shows that test is still printed even though the timeout has expired.
This occurs because there is no straightforward method in Go to forcefully interrupt the execution of a running goroutine. Go operates on a fork-join concurrency model, where a new goroutine is created as a separate execution thread. Once created, the scheduling and handling of goroutines becomes a part of the Go runtime's responsibility.
To address this issue, it is recommended to adopt synchronization techniques that allow for more granular control over goroutine behavior.
The above is the detailed content of How to Cancel a Go Goroutine's Execution After a Timeout?. For more information, please follow other related articles on the PHP Chinese website!