```go
package main
import "fmt"
import "sync"
func main(){
var wg sync.WaitGroup
wg.Add(1)
f(wg)
wg.Wait()
fmt.Println("exit from main")
}
func f(wg sync.WaitGroup){
defer func(){
if e := recover(); e != nil {
fmt.Println("caught panic")
}
wg.Done()
}()
go func(){
defer func(){
if e := recover(); e != nil {
fmt.Println(e)
}
}()
panic(1)
}()
}
```
执行结果:
```
1
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xc42000e23c)
/home/zenglin/Downloads/go1.8/src/runtime/sema.go:47 +0x34
sync.(*WaitGroup).Wait(0xc42000e230)
/home/zenglin/Downloads/go1.8/src/sync/waitgroup.go:131 +0x7a
main.main()
/mnt/hgfs/src/test/test.go:10 +0x6c
exit status 2
```
怎么会所有的协程都阻塞?![无标题.png](https://static.studygolang.com/171201/f06243166bce3c860b0b5b004526c855.png)
我是这样理解的,进入函数f:
(1) 先执行go ,然后panic
(2)执行goroutine 里面的 defer,不管 go里面的 defer有没有执行完,然后就执行f函数的go外面的 defer
请问我这样理解正确吗?
#4
更多评论