How can I exit from a goroutine (from within) from anywhere on the stack?

StackOverflow https://stackoverflow.com/questions/17952953

  •  04-06-2022
  •  | 
  •  

Вопрос

For example:

func foo() {
    // How can I exit the goroutine here?
}

func bar() {
    foo()
}

func goroutine() {
    for {
        bar()
    }
}

func main() {
    go goroutine()
}

How can I exit the goroutine directly from foo() or bar()? I was thinking of maybe using panic and recover, but I am not sure exactly how they work. (With traditional exception handling, I would just wrap the body of goroutine() in a try block and throw an exception when I want to exit.)

EDIT: If I used panic, do I even need to recover()?

Это было полезно?

Решение

There is a function in runtime for exiting a goroutine: http://golang.org/pkg/runtime/#Goexit

runtime.Goexit()

If your panic escapes the goroutine, the entire program panics. So yes, you would need to recover.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top