Home > Backend Development > Golang > How Can Go\'s `recover()` Function Keep Multiple Goroutines Running After a Panic?

How Can Go\'s `recover()` Function Keep Multiple Goroutines Running After a Panic?

Patricia Arquette
Release: 2024-11-26 08:24:09
Original
792 people have browsed it

How Can Go's `recover()` Function Keep Multiple Goroutines Running After a Panic?

Keeping Multiple Goroutines Running in the Event of a Crash

When working with multiple goroutines in Go, it's essential to consider scenarios where one goroutine may crash or panic, potentially affecting the entire program. To prevent this, the program must handle these situations gracefully, allowing the other goroutines to continue running.

Using the Recover Function

Go provides the built-in recover() function that enables handling panics and recovering from them. To use this function, it must be called within a deferred function. In this way, if a panic occurs, it is captured and the program resumes its execution after the deferred function completes.

Here's an example of how recover() can be utilized:

func doPanic() {
    fmt.Println("About to panic")
    panic("test")
}

func protect(f func()) {
    defer func() {
        if err := recover(); err != nil {
            fmt.Printf("Recovered: %v", err)
        }
    }()

    f()
}

func main() {
    go protect(doPanic)

    for {
        time.Sleep(time.Second)
        fmt.Println("Tick")
    }
}
Copy after login

Explanation

  • doPanic is a function that deliberately panics.
  • protect is a helper function that wraps a function as a goroutine, trapping any panics using a deferred function.
  • In main, protect(doPanic) is launched as a goroutine to demonstrate panic recovery.

Output

When this code is executed, it will output:

About to panic
Recovered: test
Tick
Tick
Tick
...
Copy after login

This illustrates that even though doPanic caused a panic, the program continued running due to the recover() call, allowing the other goroutine to continue executing indefinitely.

It's important to note that while recover() allows the program to continue running, it does not prevent the underlying panic from occurring. Therefore, it's still essential to identify and address the root cause of the panic to prevent it from happening again in the future.

The above is the detailed content of How Can Go\'s `recover()` Function Keep Multiple Goroutines Running After a Panic?. 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