我有一个全局映射,并且我使用许多goroutines无限制地同时编写映射。然后,这当然会引起恐慌。因此,我添加了恢复方法以应对紧急情况。但是似乎它们没有什么区别。
我的代码如下:
var m = make(map[int]int)
func main(){
defer func(){
if err:=recover();err!=nil{
fmt.Printf("=====recover in main:%s\n",err)
}
}()
count := 1000
for i:=0;i<count;i++{
go AddEle()
}
}
func AddEle(){
defer func(){
if err:=recover();err!=nil{
fmt.Printf("====recover in child goroutines:%s",err)
}
}()
for i:=1;i<1000;i++{
m[i] = i
}
}
,输出如下:
fatal error: concurrent map writesc
goroutine 5 [running]:
runtime.throw(0x666514, 0x15)
/usr/local/go/src/runtime/panic.go:605 +0x95 fp=0xc42002ff48
sp=0xc42002ff28 pc=0x42b2a5
runtime.mapassign_fast64(0x61c360, 0xc42007cbd0, 0x1, 0x0)
/usr/local/go/src/runtime/hashmap_fast.go:519 +0x3d2
fp=0xc42002ffa8 sp=0xc42002ff48 pc=0x40dbb2
main.AddEle()
/home/geek/go/work/src/web/main.go:34 +0x6a fp=0xc42002ffe0
sp=0xc42002ffa8 pc=0x5e257a
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:2337 +0x1 fp=0xc42002ffe8
sp=0xc42002ffe0 pc=0x458821
created by main.main
c/home/geek/go/work/src/web/main.go:22 +0x5at.
所以我想知道为什么恢复没有效果。
答案 0 :(得分:2)