go语言学习--map的并发
go提供了一种叫map的数据结构,可以翻译成映射,对应于其他语言的字典、哈希表。借助map,可以定义一个键和值,然后可以从map中获取、设置和删除这个值,尤其适合数据查找的场景。但是map的使用有一定的限制,如果是在单个协程中读写map,那么不会存在什么问题,如果是多个协程并发访问一个map,有可能会导致程序退出,并打印下面错误信息:
fatal error: concurrent map read and map write
上面的这个错误不是每次都会遇到的,如果并发访问的协程数不大,遇到的可能性就更小了。例如下面的程序:
package main func main() {
Map := make(map[int]int) for i := 0; i < 10; i++ {
go writeMap(Map, i, i)
go readMap(Map, i)
} } func readMap(Map map[int]int, key int) int {
return Map[key]
} func writeMap(Map map[int]int, key int, value int) {
Map[key] = value
}
只循环了10次,产生了20个协程并发访问map,程序基本不会出错,但是如果将循环次数变大,比如10万,运行下面程序基本每次都会出错:
package main func main() {
Map := make(map[int]int) for i := 0; i < 100000; i++ {
go writeMap(Map, i, i)
go readMap(Map, i)
} } func readMap(Map map[int]int, key int) int {
return Map[key]
} func writeMap(Map map[int]int, key int, value int) {
Map[key] = value
}
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的安全并发访问,示例代码如下:
package main import "sync" type SafeMap struct {
sync.RWMutex
Map map[int]int
} func main() {
safeMap := newSafeMap(10) for i := 0; i < 100000; i++ {
go safeMap.writeMap(i, i)
go safeMap.readMap(i)
} } func newSafeMap(size int) *SafeMap {
sm := new(SafeMap)
sm.Map = make(map[int]int)
return sm } func (sm *SafeMap) readMap(key int) int {
sm.RLock()
value := sm.Map[key]
sm.RUnlock()
return value
} func (sm *SafeMap) writeMap(key int, value int) {
sm.Lock()
sm.Map[key] = value
sm.Unlock()
}
但是通过读写锁控制map的并发访问时,会导致一定的性能问题,不过能保证程序的安全运行,牺牲点性能问题是可以的。
参考
作者:songleo
链接:https://www.jianshu.com/p/10a998089486
go语言学习--map的并发的更多相关文章
- go语言学习--map中键值得删除
测试 map1 中是否存在 key1: 在例子 8.1 中,我们已经见过可以使用 val1 = map1[key1] 的方法获取 key1 对应的值 val1.如果 map 中不存在 key1,val ...
- go语言学习--map类型的切片
今天在项目中遇到了一个切片的map,记录下map切片的使用 package main import "fmt" func main() { // Version A: items ...
- Go语言学习——map
map 映射关系容器 内部使用散列表(hash)实现 map是引用类型 必须初始化才能使用 无序的基于key-value的数据结构 map定义 map的定义语法: map[KeyType]ValueT ...
- Go语言学习笔记十三: Map集合
Go语言学习笔记十三: Map集合 Map在每种语言中基本都有,Java中是属于集合类Map,其包括HashMap, TreeMap等.而Python语言直接就属于一种类型,写法上比Java还简单. ...
- Go语言学习之路
我关于Go语言的博客原本发布于我的个人网站:wwww.liwenzhouu.com.但是被某些人抄怕了,没办法只好搬运到博客园. 我的Go语言学习之路 2015年底我因为工作原因接触到了Go语言,那时 ...
- go语言学习笔记
Go语言学习基本类型Bool 取值范围:true,false (不可以用数字代替)Int/uint 根据平台可能为32或64位int8/uint8 长度:1字节 取值范围-128~127/0~255b ...
- GO语言学习笔记(一)
GO语言学习笔记 1.数组切片slice:可动态增长的数组 2.错误处理流程关键字:defer panic recover 3.变量的初始化:以下效果一样 `var a int = 10` `var ...
- Haskell语言学习笔记(88)语言扩展(1)
ExistentialQuantification {-# LANGUAGE ExistentialQuantification #-} 存在类型专用的语言扩展 Haskell语言学习笔记(73)Ex ...
- Go语言学习笔记十二: 范围(Range)
Go语言学习笔记十二: 范围(Range) rang这个关键字主要用来遍历数组,切片,通道或Map.在数组和切片中返回索引值,在Map中返回key. 这个特别像python的方式.不过写法上比较怪异使 ...
随机推荐
- LeetCode - Kth Largest Element in a Stream
Design a class to find the kth largest element in a stream. Note that it is the kth largest element ...
- 【BZOJ2594】【WC2006】水管局长
日……又被傻B错坑了一整天…… 原题: SC省MY市有着庞大的地下水管网络,嘟嘟是MY市的水管局长(就是管水管的啦),嘟嘟作为水管局长的工作就是:每天供水公司可能要将一定量的水从x处送往y处,嘟嘟需要 ...
- mysql export query result
1 . export by shell a.sql use dbname; SELECT id,iab_num FROM iab_list ; mysql -h host -uusername -P3 ...
- mysql优化查询
使用索引查询 MariaDB [test]> explain select * from te where id=22; #在没有增加索引情况下,rows为7,即查询行数 +------+--- ...
- MySQL Config--参数system_time_zone和参数time_zone
全局参数system_time_zone系统时区,在MySQL启动时会检查当前系统的时区并根据系统时区设置全局参数system_time_zone的值. The system time zone. W ...
- openresty 使用lua-resty-shell 执行shell 脚本
lua-resty-shell 是一个很不错的项目,让我们可以无阻塞的执行shell命令,之间的通信 是通过socket (一般是unix socket) 环境准备 docker-compose 文件 ...
- IBM MQ相关 ---- 系列文章
原 IBM websphere MQ远程队列的简单配置 转 MQ7.5以后的权限问题解决 原 MQ--API总结 转 连接IBM MQ原因码报2035的错误解决办法 原 Java连接MQ的实例 转 通 ...
- MySQL插入,更新,删除数据
插入 单行插入 1.insert into 表名 values(col1_value,col2_value,...); 每个列必须提供一个值,如果没有值,要提供NULL值 每个列必须与它在表中定义的次 ...
- Python之安装pip
安装Python之后,命令行语句定位到其安装目录下的Scripts目录 如我的安装目录是:D:\python\Scripts 然后执行命令:easy_install.exe pip就会开始安装pip ...
- 单节点 Elasticsearch 出现 unassigned shards 原因及解决办法
根本原因: 是因为集群存在没有启用的副本分片,我们先来看一下官网给出的副本分片的介绍: 副本分片的主要目的就是为了故障转移,正如在 集群内的原理 中讨论的:如果持有主分片的节点挂掉了,一个副本分片就会 ...