迹忆客 计算机编程题库

题库 > Go > Go 笔试题精选 练习:14

Go 笔试题精选

高并发情况下,map常见问题分析 代码如下,正确的是() ```go 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 } ```
  • 程序正常执行
  • 程序根本编译不过
  • fatal error: concurrent map read and map write
正确答案是:C
正确率:93%

解析:

官方解释:

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.

大致意思就是说,并发访问map是不安全的,会出现未定义行为,导致程序退出。所以如果希望在多协程s)中并发访问map,必须提供某种同步机制,一般情况下通过读写锁sync.RWMutex实现对map的并发访问控制,将map和sync.RWMutex封装一下,可以实现对map的安全并发访问。

同时Go1.9版本之后,已经支持,sync包下:

func (m *Map) Delete(key interface{})
func (m *Map) Load(key interface{}) (value interface{}, ok bool)
func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)
func (m *Map) Range(f func(key, value interface{}) bool)
func (m *Map) Store(key, value interface{})

查看笔记

扫码一下
查看教程更方便