最新标签
站点统计
  • 文章 3631
  • 标签 378
  • 分类 5
  • 留言 66
  • 用户 3
  • 浏览 1341740
  • 运营 1154 天
关于我们
  • 嘟嘟
  • 互联网前端工程师
  • 湘ICP备20000000号-1
Go使用sync.Map来解决map的并发操作问题
嘟嘟 2022-11-25 301

前言

在 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> false
1 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使用sync.Map来解决map的并发操作问题的文章就介绍到这了,更多相关Go语言 sync.Map解决map并发操作内容请搜索M135模板网以前的文章或继续浏览下面的相关文章希望大家以后多多支持M135模板网!

Comments | 0 条评论
25202211https://www.c721.com/zb_users/theme/Moments/images/1.pngGo使用sync.Map来解决map的并发操作问题前言 在 Golang 中 map 不是并发安全的,自.....https://www.c721.com/zb_users/theme/Moments/plugin/img/poster_okclose.pnghttps://www.c721.com/zb_users/theme/Moments/plugin/api.php?url=https://www.c721.com/zb_users/theme/Moments/plugin/img/poster_zw.png721模板网
联系客服

客服QQ

客服微信

图片背景 颜色背景
布局切换 黑暗日光 定时刷新 监听内容 小窗模式
  • 默认默认
  • 默认