Home >Backend Development >Golang >How Can I Keep My Go Goroutines Running Even After a Panic?
Keeping Goroutines Running Despite Crashes
In Go, goroutines are powerful but can be susceptible to crashes due to errors or panics. To ensure that one goroutine's failure doesn't impact others, developers may wonder if there's a way to keep unaffected goroutines running.
To recover from panics, the built-in recover() function is utilized. It allows you to catch a panic within a deferred function. The following helper function, protect(), employs this mechanism to launch goroutines with panic recovery:
func protect(f func()) { defer func() { if err := recover(); err != nil { log.Printf("Recovered: %v", err) } }() f() }
To use this protection, simply pass your function as an argument to protect(). By wrapping this call within a for loop that continuously prints "tick," we can demonstrate how the goroutine protected by protect() will continue running even if a panic occurs in another goroutine:
func main() { go protect(doPanic) for { time.Sleep(time.Second) fmt.Println("tick") } }
This test application will output:
2021/03/04 14:12:31 about to panic 2021/03/04 14:12:31 Recovered: test tick tick tick ...
As you can see, the panic in the doPanic function is recovered and handled, while the protected goroutine continues running and printing "tick." This approach effectively isolates goroutines from panics, ensuring that a single failure doesn't propagate and crash the entire application.
The above is the detailed content of How Can I Keep My Go Goroutines Running Even After a Panic?. For more information, please follow other related articles on the PHP Chinese website!