例如:
func foo() {
// How can I exit the goroutine here?
}
func bar() {
foo()
}
func goroutine() {
for {
bar()
}
}
func main() {
go goroutine()
}
如何直接从 foo()
或 bar()
退出 goroutine?我正在考虑使用 panic
和 recover
,但我不确定它们是如何工作的。 (对于传统的异常处理,我只是将 goroutine()
的主体包装在 try
block 中,并在我想退出时抛出异常。)
编辑:如果我使用了panic
,我还需要recover()
吗?
最佳答案
运行时有一个退出goroutine的函数:http://golang.org/pkg/runtime/#Goexit
runtime.Goexit()
如果您的 panic 逃脱了 goroutine,整个程序都会 panic。所以是的,你需要恢复。
关于go - 我怎样才能从堆栈的任何地方(从内部)退出 goroutine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17952953/