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的方式.不过写法上比较怪异使 ...
随机推荐
- KMP算法自我理解 和 模板
字符串 abcd abc abcd abc 匹配串 cdabcd 匹配串的 next 0 0 0 0 1 2: 开始匹配 abcd abc abcd abc cd abc d a,d 匹配失 ...
- CH4908 Race
题意 4908 Race 0x49「数据结构进阶」练习 描述 给定一棵 N 个节点的树,每条边带有一个权值. 求一条简单路径,路径上各条边的权值和等于K,且路径包含的边的数量最少. 输入格式 第一行两 ...
- SpringCloud学习
1.SpringCloud的参考博客1 首先主要遇到的问题就是1.写好项目然后放到tomcat或者其他的容器中,然后稍微一点修改就要整个项目重新发布,非常麻烦,这就是微服务出现的契机了 基础知识 PS ...
- linux环境下配置mysql双主复制
简单来说,双主复制就是让两台mysql服务器中的数据保持同步,可以用来实现灾备和负载均衡 主机1 IP:192.168.200.128 主机2 IP:192.168.200.131 两台主机系统均为c ...
- Introducing Makisu: Uber’s Fast, Reliable Docker Image Builder for Apache Mesos and Kubernetes
转自:https://eng.uber.com/makisu/?amp To ensure the stable, scalable growth of our diverse tech stack, ...
- Embedded SW uses STL or not
As the complexity increasing of embedded software, more and more projects/products use C++ as the im ...
- python查看及修改当前的工作路径
在pycharm中使用jupyter的时候,有时候需要查看当前的工作路径,然后需要修改当前的路径. 获取当前工作目录 os.getcwd() #用以获取当前的工作目录 改变当前工作目录 os.chdi ...
- C# to IL 12 Arrays(数组)
An array is a contiguous block of memory that stores values of the same type. These valuesare an ind ...
- oracle-闪回技术2
闪回版本查询,用到了附加日志 闪回事务查询 http://blog.csdn.net/laoshangxyc/article/details/12405459 这个博客的备份与恢复可以参考 ##### ...
- 收藏一篇 Python 文本框操作命令
原文地址:https://www.cnblogs.com/onlyfu/archive/2013/03/07/2947473.html 属性(Options) background(bg) borde ...