如何在堆栈的任何位置从goroutine中退出(从内部)?

huangapple go评论97阅读模式
英文:

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

问题

例如:

func foo() {
    // 如何在这里直接退出 goroutine?
}

func bar() {
    foo()
}

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

func main() {
    go goroutine()
}

我如何在 foo()bar() 中直接退出 goroutine?我在考虑可能使用 panicrecover,但我不确定它们的工作原理。(使用传统的异常处理,我只需将 goroutine() 的代码块放在 try 块中,并在想要退出时抛出异常。)

编辑:如果我使用 panic,我是否需要 recover()

英文:

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()?

答案1

得分: 5

如果你的panic逃离了goroutine,整个程序都会panic。所以是的,你需要进行恢复。

英文:

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.

huangapple
  • 本文由 发表于 2013年7月31日 00:53:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/17952953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定