英文:
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?我在考虑可能使用 panic
和 recover
,但我不确定它们的工作原理。(使用传统的异常处理,我只需将 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论