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的并发访问时,会导致一定的性能问题,不过能保证程序的安全运行,牺牲点性能问题是可以的。

参考

go官方博客:https://blog.golang.org/go-maps-in-action

go FAQ:https://golang.org/doc/faq#atomic_maps

作者:songleo
链接:https://www.jianshu.com/p/10a998089486

go语言学习--map的并发的更多相关文章

  1. go语言学习--map中键值得删除

    测试 map1 中是否存在 key1: 在例子 8.1 中,我们已经见过可以使用 val1 = map1[key1] 的方法获取 key1 对应的值 val1.如果 map 中不存在 key1,val ...

  2. go语言学习--map类型的切片

    今天在项目中遇到了一个切片的map,记录下map切片的使用 package main import "fmt" func main() { // Version A: items ...

  3. Go语言学习——map

    map 映射关系容器 内部使用散列表(hash)实现 map是引用类型 必须初始化才能使用 无序的基于key-value的数据结构 map定义 map的定义语法: map[KeyType]ValueT ...

  4. Go语言学习笔记十三: Map集合

    Go语言学习笔记十三: Map集合 Map在每种语言中基本都有,Java中是属于集合类Map,其包括HashMap, TreeMap等.而Python语言直接就属于一种类型,写法上比Java还简单. ...

  5. Go语言学习之路

    我关于Go语言的博客原本发布于我的个人网站:wwww.liwenzhouu.com.但是被某些人抄怕了,没办法只好搬运到博客园. 我的Go语言学习之路 2015年底我因为工作原因接触到了Go语言,那时 ...

  6. go语言学习笔记

    Go语言学习基本类型Bool 取值范围:true,false (不可以用数字代替)Int/uint 根据平台可能为32或64位int8/uint8 长度:1字节 取值范围-128~127/0~255b ...

  7. GO语言学习笔记(一)

    GO语言学习笔记 1.数组切片slice:可动态增长的数组 2.错误处理流程关键字:defer panic recover 3.变量的初始化:以下效果一样 `var a int = 10` `var ...

  8. Haskell语言学习笔记(88)语言扩展(1)

    ExistentialQuantification {-# LANGUAGE ExistentialQuantification #-} 存在类型专用的语言扩展 Haskell语言学习笔记(73)Ex ...

  9. Go语言学习笔记十二: 范围(Range)

    Go语言学习笔记十二: 范围(Range) rang这个关键字主要用来遍历数组,切片,通道或Map.在数组和切片中返回索引值,在Map中返回key. 这个特别像python的方式.不过写法上比较怪异使 ...

随机推荐

  1. linux---文件颜色含义

    下面是linux系统约定不同类型文件默认的颜色: 白色:表示普通文件 蓝色:表示目录 绿色:表示可执行文件 红色:表示压缩文件 浅蓝色:链接文件 红色闪烁:表示链接的文件有问题 黄色:表示设备文件 灰 ...

  2. 【mysql】索引原理-MySQL索引原理以及查询优化

    转载:https://www.cnblogs.com/bypp/p/7755307.html 一.介绍 1.什么是索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性 ...

  3. linux网络编程概念(一)

    AF表示地址族(address family) PF表示协议族(protocol family) domain参数 AF_UNIX 内核中通信 sockaddr_un AF_INET 通过ipv4 s ...

  4. MySQL Config--参数system_time_zone和参数time_zone

    全局参数system_time_zone系统时区,在MySQL启动时会检查当前系统的时区并根据系统时区设置全局参数system_time_zone的值. The system time zone. W ...

  5. python Console menu

    I just finished a demo which is to provide an easy way to control hardware resources of A sample. Th ...

  6. Producer and consumer

    Below is from wiki, just for study & record. In computing, the producer–consumer problem (also k ...

  7. MySQL创建表,更新表,删除表,重命名表

    创建表 mysql> create table 表名( -> 列名 数据类型 是否为空 auto_increment, -> 列名 数据类型 是否为空... -> ... -& ...

  8. 学习concurrency programming进展

    看了一段时间的actor model,goroutine之类的东东,最近在github上写了个简单的框架, 注:未做大量测试,仅供学习用,勿用于生产用途 链接: https://github.com/ ...

  9. vue-cli、create-react-app 项目如何查看打包分析?

    vue-cli.create-react-app 项目如何查看打包分析? 项目 如何查看打包分析 vue-cli 创建的项目 已经集成 webpack-bundle-analyzer,运行npm ru ...

  10. xshell 5中文破解版下载

    xshell 5破解版是一款功能强大的终端模拟软件,支持Telnet.Rlogin.SSH.SFTP.Serial等远程协议,让用户能通过互联网直接连接远程主机.用户通过xshell 5破解版能轻松和 ...