```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)
`go`函数有可能还没执行就会执行 `f` 函数,多试几次就会出现![image.png](https://static.studygolang.com/171226/dededdca4b8c8e5ecefa83616c2bb45f.png)
#5
更多评论