golang 使用defer、panic、recover的问题
发布时间:2020-12-16 18:12:57 所属栏目:大数据 来源:网络整理
导读:defer 今天开发一个功能,犯了个小错误,记录下。简单代码如下: package mainimport ( "fmt" "sync" "time" )func main() { var mt sync.Mutex for i := 0 ; i 10 ; i++ { go func( index int ) { for j := 0 ; j 3 ; j++ { mt.Lock() defer func() { mt.Un
defer今天开发一个功能,犯了个小错误,记录下。简单代码如下: package main
import (
"fmt"
"sync"
"time"
)
func main() {
var mt sync.Mutex
for i := 0; i < 10; i++ {
go func(index int) {
for j := 0; j < 3; j++ {
mt.Lock()
defer func() {
mt.Unlock()
fmt.Println("release done")
}()
fmt.Printf("%d_%dn",index,j)
}
}(i)
}
time.Sleep(time.Second * time.Duration(1))
fmt.Println("finish!")
}
执行后发现协成一直卡在了defer释放的地方,而把defer mt.Unlock()直接放在打印后,采用手动释放的方式就没问题。 panic、recoverpackage main
import "fmt"
func main() {
defer_call()
}
func defer_call() {
defer func() {
if err := recover(); err != nil {
fmt.Println(err) //此处的err其实是panic传入的值
}
}()
defer func() { fmt.Println("打印前") }()
defer func() { fmt.Println("打印中") }()
defer func() { fmt.Println("打印后") }()
panic("触发异常") //需要使用recover进行捕获
}
执行结果: 触发异常 打印后 打印中 打印前 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |