go map的并发读写

xyzasd01 · · 5417 次点击
楼上正解,读的地方加个读锁`RLock`即可
#2
更多评论
polaris
社区,需要你我一同完善!
你只顾着写的时候加锁,读也得加。`fmt.Println(counter)` 你把它给忘了!
#1
所有崩溃都可以很容易在崩溃后打印的调用堆栈里面找到原因 fatal error: concurrent map iteration and map write goroutine 7 [running]: runtime.throw(0x4aae87, 0x26) /usr/local/go/src/runtime/panic.go:596 +0x95 fp=0xc42003a840 sp=0xc42003a820 runtime.mapiternext(0xc420086060) /usr/local/go/src/runtime/hashmap.go:737 +0x7ee fp=0xc42003a8f0 sp=0xc42003a840 reflect.mapiternext(0xc420086060) /usr/local/go/src/runtime/hashmap.go:1156 +0x2b fp=0xc42003a908 sp=0xc42003a8f0 reflect.Value.MapKeys(0x490200, 0xc42007a078, 0xb5, 0x0, 0x76, 0x2) /usr/local/go/src/reflect/value.go:1112 +0x1bc fp=0xc42003a9b8 sp=0xc42003a908 fmt.(*pp).printValue(0xc420082000, 0x490200, 0xc42007a078, 0xb5, 0x76, 0x1) /usr/local/go/src/fmt/print.go:741 +0xedf fp=0xc42003abb0 sp=0xc42003a9b8 fmt.(*pp).printValue(0xc420082000, 0x492c40, 0xc42007a060, 0x99, 0x76, 0x0) /usr/local/go/src/fmt/print.go:778 +0x21de fp=0xc42003ada8 sp=0xc42003abb0 fmt.(*pp).printArg(0xc420082000, 0x492c40, 0xc42007a060, 0x76) /usr/local/go/src/fmt/print.go:682 +0x217 fp=0xc42003ae30 sp=0xc42003ada8 fmt.(*pp).doPrintln(0xc420082000, 0xc42003af98, 0x1, 0x1) /usr/local/go/src/fmt/print.go:1138 +0xa1 fp=0xc42003aea8 sp=0xc42003ae30 fmt.Fprintln(0x4f7160, 0xc42000c018, 0xc42003af98, 0x1, 0x1, 0xc42007a060, 0xc42003afa8, 0xc42007a060) /usr/local/go/src/fmt/print.go:247 +0x5c fp=0xc42003af10 sp=0xc42003aea8 fmt.Println(0xc42003af98, 0x1, 0x1, 0xc42007a060, 0x0, 0x0) /usr/local/go/src/fmt/print.go:257 +0x57 fp=0xc42003af60 sp=0xc42003af10 main.main.func2(0xc42000a1a0) /home/marlon/projects/t.go:26 +0xb1 fp=0xc42003afd8 sp=0xc42003af60 runtime.goexit()
#3