实现说明
在 worker 内部就地 recover goroutine panic以函数 worker、main为骨架。
执行扇出到 goroutine,再经 channel 交接收拢。清理调用被推迟到函数出口——正常返回、提前返回、panic 全都覆盖。
使用要点
- 直接运行文件,输出会带上标签,比如
process still alive——输出的每一行都能指回产生它的那次调用。 main的演示流程是worker——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「在 worker 内部就地 recover goroutine panic」会打印什么?
整个文件跑完,输出行以 process still alive 这类前缀开头。
入口签名:func worker(id int, out chan<- string)
核心语句
func worker(id int, out chan<- string) {
defer func() {
if r := recover(); r != nil {
out <- fmt.Sprintf("task %d recovered: %v", id, r)
}
}()
if id%2 == 1 {
panic("bad index")
}
out <- fmt.Sprintf("task %d finished", id)
}
func main() {
out := make(chan string, 1)
go worker(0, out)
fmt.Println(<-out)
go worker(1, out)
fmt.Println(<-out)
// 没有 recover 的 goroutine panic 会直接终止整个进程,无法在别处捕获
fmt.Println("process still alive")
}
代码示例
package main
import "fmt"
// recover 必须写在 panic 源头所在的 goroutine 内:
// 主 goroutine 的 defer 接不到其他 goroutine 抛出的 panic
func worker(id int, out chan<- string) {
defer func() {
if r := recover(); r != nil {
out <- fmt.Sprintf("task %d recovered: %v", id, r)
}
}()
if id%2 == 1 {
panic("bad index")
}
out <- fmt.Sprintf("task %d finished", id)
}
func main() {
out := make(chan string, 1)
go worker(0, out)
fmt.Println(<-out)
go worker(1, out)
fmt.Println(<-out)
// 没有 recover 的 goroutine panic 会直接终止整个进程,无法在别处捕获
fmt.Println("process still alive")
}