I have a global map, and I use many goroutines to write map concurrently without without limit. Then this of course will cause panic. So I add recover method in order to deal with panic. But it seemed they make no difference.
my code as below:
var m = make(map[int]int)
func main(){
defer func(){
if err:=recover();err!=nil{
fmt.Printf("=====recover in main:%s
",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
}
}
and the output as below:
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.
so I want to know why recover dont make effect.
The recover()
function handles panics.
When the runtime detects a concurrent map access, the runtime exits the process with a call to fatalthrow.
The runtime does not panic in this situation, therefore the recover handler is not invoked.