go 笔试题精选练习题|——迹忆客-ag捕鱼王app官网

题库 > go > 练习:45

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
正确率:98%

解析:

官方解释:

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{})

查看笔记

扫码一下
查看教程更方便
网站地图