进行并发自测时进程突然终止,错误为“fatal error: concurrent map writes”,原来golang原生map类型是非并发安全的,要使用sync.Map才能并发写。
package main
import (
"fmt"
"sync"
)
type Test struct {
MemA string
MemB string
MemC int
}
func main() {
var TMap sync.Map
TMap.Store("test1", Test{MemA: "a", MemB: "b", MemC: 1})
TMap.Store("test2", Test{MemA: "c", MemB: "d", MemC: 2})
for _, key := range []string{"test1", "test2"} {
if res, ok := TMap.Load(key); ok {
data := res.(Test) // 将取出的接口类型数据转换成结构体
fmt.Println(data.MemA, data.MemB, data.MemC)
}
}
}
运行结果
➜ go run test.go
a b 1
c d 2