go语言学习--map的并发
go提供了一种叫map的数据结构,可以翻译成映射,对应于其他语言的字典、哈希表。借助map,可以定义一个键和值,然后可以从map中获取、设置和删除这个值,尤其适合数据查找的场景。但是map的使用有一定的限制,如果是在单个协程中读写map,那么不会存在什么问题,如果是多个协程并发访问一个map,有可能会导致程序退出,并打印下面错误信息:
fatal error: concurrent map read and map write
上面的这个错误不是每次都会遇到的,如果并发访问的协程数不大,遇到的可能性就更小了。例如下面的程序:
1 package main 2 3 func main() { 4 Map := make(map[int]int) 5 6 for i := 0; i < 10; i++ { 7 go writeMap(Map, i, i) 8 go readMap(Map, i) 9 } 10 11 } 12 13 func readMap(Map map[int]int, key int) int { 14 return Map[key] 15 } 16 17 func writeMap(Map map[int]int, key int, value int) { 18 Map[key] = value 19 }
只循环了10次,产生了20个协程并发访问map,程序基本不会出错,但是如果将循环次数变大,比如10万,运行下面程序基本每次都会出错:
1 package main 2 3 func main() { 4 Map := make(map[int]int) 5 6 for i := 0; i < 100000; i++ { 7 go writeMap(Map, i, i) 8 go readMap(Map, i) 9 } 10 11 } 12 13 func readMap(Map map[int]int, key int) int { 14 return Map[key] 15 } 16 17 func writeMap(Map map[int]int, key int, value int) { 18 Map[key] = value 19 }
go官方博客有如下说明:
Maps are not safe for concurrent use: it's not defined what happens when you read and write to them simultaneously. If you need to read from and write to a map from concurrently executing goroutines, the accesses must be mediated by some kind of synchronization mechanism. One common way to protect maps is with sync.RWMutex.
go FAQ解释如下:
After long discussion it was decided that the typical use of maps did not require safe access from multiple goroutines, and in those cases where it did, the map was probably part of some larger data structure or computation that was already synchronized. Therefore requiring that all map operations grab a mutex would slow down most programs and add safety to few. This was not an easy decision, however, since it means uncontrolled map access can crash the program.
大致意思就是说,并发访问map是不安全的,会出现未定义行为,导致程序退出。所以如果希望在多协程中并发访问map,必须提供某种同步机制,一般情况下通过读写锁sync.RWMutex实现对map的并发访问控制,将map和sync.RWMutex封装一下,可以实现对map的安全并发访问,示例代码如下:
1 package main 2 3 import "sync" 4 5 type SafeMap struct { 6 sync.RWMutex 7 Map map[int]int 8 } 9 10 func main() { 11 safeMap := newSafeMap(10) 12 13 for i := 0; i < 100000; i++ { 14 go safeMap.writeMap(i, i) 15 go safeMap.readMap(i) 16 } 17 18 } 19 20 func newSafeMap(size int) *SafeMap { 21 sm := new(SafeMap) 22 sm.Map = make(map[int]int) 23 return sm 24 25 } 26 27 func (sm *SafeMap) readMap(key int) int { 28 sm.RLock() 29 value := sm.Map[key] 30 sm.RUnlock() 31 return value 32 } 33 34 func (sm *SafeMap) writeMap(key int, value int) { 35 sm.Lock() 36 sm.Map[key] = value 37 sm.Unlock() 38 }
但是通过读写锁控制map的并发访问时,会导致一定的性能问题,不过能保证程序的安全运行,牺牲点性能问题是可以的。
参考
作者:songleo
链接:https://www.jianshu.com/p/10a998089486
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能