go语言坑之并发访问map

作者: songleo | 来源:发表于2017-04-21 21:07 被阅读2643次

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

本次荐书:买个好房子
买个好房子买个好房子

相关文章

  • go语言坑之并发访问map

    go提供了一种叫map的数据结构,可以翻译成映射,对应于其他语言的字典、哈希表。借助map,可以定义一个键和值,然...

  • Go语言高并发Map解决方案

    Go语言高并发Map解决方案 Go语言基础库中的map不是并发安全的,不过基于读写锁可以实现线程安全;不过在Go1...

  • Golang goroutine 与 map 并发的采坑事件

    goroutine 与 map 并发的采坑事件 1. goroutine 与map 的并发读写操作 在Go 1.6...

  • 第14章-并发性Concurrency

    并发性Concurrency 1.1 什么是并发 Go是并发语言,而不是并行语言。在讨论如何在Go中进行并发处理之...

  • Golang(十四) 并发性Concurrency

    并发性Concurrency 1.1 什么是并发 Go是并发语言,而不是并行语言。在讨论如何在Go中进行并发处理之...

  • go print "%+v" 可以打印私有变量;reflect遍

    go print函数“%+v”可以访问私有变量(如果私有变量里有map,打印相当于读,会有map并发读写问题)比如...

  • 10.map

    Go语言基础之map | Golang Go语言中提供的映射关系容器为map,其内部使用散列表(hash)实现。 ...

  • map与sync.Map

    Go 语言原生 map 并不是线程安全的,对它进行并发读写操作的时候,需要加锁。而 sync.map 则是一种并发...

  • Go语言——sync.Map详解

    Go语言——sync.Map详解 sync.Map是1.9才推荐的并发安全的map,除了互斥量以外,还运用了原子操...

  • Go语言并发

    Go语言并发 Go语言级别支持协程,叫做goroutine Go 语言从语言层面支持并发和并行的开发操作 Go并发...

网友评论

  • 米洛丶:感谢博主分享, 点个赞。
    songleo:@邻居的尾巴 :smile:
  • songleo:《买个好房子》这本书尤其适合想买二手房的同学,墙裂推荐:smile:

本文标题:go语言坑之并发访问map

本文链接:https://www.haomeiwen.com/subject/yhrjzttx.html