前言
在 Golang
中 map
不是并发平安的,自 1.9 才引入了 sync.Map
,sync.Map
的引入的确解决了 map
的并发平安问题,不过 sync.Map
却没有实现 len()
函数,如果想要计算 sync.Map
的长度,略微有点麻烦,须要应用 Range
函数。
map 并发操作呈现问题
func main() { demo := make(map[int]int) go func() { for j := 0; j < 1000; j++ { demo[j] = j } }() go func() { for j := 0; j < 1000; j++ { fmt.Println(demo[j]) } }() time.Sleep(time.Second * 1)}
执行输入:
fatal error: concurrent map read and map write
sync.Map 解决并发操作问题
func main() { demo := sync.Map{} go func() { for j := 0; j < 1000; j++ { demo.Store(j, j) } }() go func() { for j := 0; j < 1000; j++ { fmt.Println(demo.Load(j)) } }() time.Sleep(time.Second * 1)}
执行输入:
<nil> false1 true...999 true
计算 map 长度
func main() { demo := make(map[int]int) for j := 0; j < 1000; j++ { demo[j] = j } fmt.Println("len of demo:", len(demo))}
执行输入:
len of demo: 1000
计算 sync.Map 长度
func main() { demo := sync.Map{} for j := 0; j < 1000; j++ { demo.Store(j, j) } lens := 0 demo.Range(func(key, value interface{}) bool { lens++ return true }) fmt.Println("len of demo:", lens)}
执行输入:
len of demo: 1000
小结
Load
加载 key 数据Store
更新或新增 key 数据Delete
删除 key 数据Range
遍历数据LoadOrStore
如果存在 key 数据则返回,反之则设置LoadAndDelete
如果存在 key 数据则删除
以上,心愿对你可能有所帮忙。
举荐浏览
- Go - 基于逃逸剖析来晋升程序性能
- Go - 应用 sync.Pool 来缩小 GC 压力
- Go - 应用 options 设计模式
- Go - json.Unmarshal 遇到的小坑
- Go - 两个在开发中需注意的小点