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 – Number of Islands
Given a -d grid map of 's (water), count the number of islands. An island is surrounded by water and ...
- MySQL Memory--内存分配相关参数
Seesion级的内存分配: max_threads(当前活跃连接数)* ( read_buffer_size(顺序读缓冲,提高顺序读效率) + read_rnd_buffer_size(随机读缓冲, ...
- Modularizing your graphQL schemas
转自: https://tomasalabes.me/blog/nodejs/graphql/2018/07/11/modularizing-graphql.html Modularizing you ...
- python结合redis模拟队列
实在无聊就写了个很小的python程序用来实现模拟redis队列的代码如下: redis_lpush.py #!/usr/bin/python3 import time import redis ...
- Java参数验证Bean Validation 框架
1.为什么要做参数校验? 参数校验和业务逻辑代码分离,参数校验代码复用,统一参数校验方式.校验不太通过时统一异常描述. 2.bean validation规范 JSR303 规范(Bean Valid ...
- apache HTML5 History 模式 配置
说明 使用的 Apache/2.4.6 版本. 文档这么写的: 但是 没说 IfModule 放在哪里 . httpd.conf 里面有大量的 IfModule . 这样的.但是实测 无效.无 ...
- 设置Redis最大占用内存
https://blog.csdn.net/happyrabbit456/article/details/54945667 Redis需要设置最大占用内存吗?如果Redis内存使用超出了设置的最大值会 ...
- centos7 如何在用户级对资源进行限制
我们已经知道,centos7上建议使用sytemd进行资源限制. 本文主要介绍如何使用systemd进行用户级资源限制. 以orange用户为例. 方案一 临时有效 配置如下: # systemctl ...
- 三重DEC加密在java中的实现
代码可以直接拷走使用,一些约定例如向量可以自行变动 引言 如今手机app五彩缤纷,确保手机用户的数据安全是开发人员必须掌握的技巧,下面通过实例介绍DES在android.ios.java平台 ...
- 转:Oracle 执行计划(Explain Plan) 说明
Oracle 执行计划(Explain Plan) 说明 原贴地址:http://blog.csdn.net/tianlesoftware/article/details/5827245 如果要分 ...