将标准 Golang 映射转换为 Sync.Map 以避免竞争条件

Converting Standard Golang Map into a Sync.Map to Avoid Race Condition

我有下面一行代码:

var a_map = make(map[string] []int)

我使用 a_map 变量的部分代码偶尔会抛出以下错误:

fatal error: concurrent map read and map write

为了尝试创建一个更强大的解决方案,一个没有此类错误的解决方案,我想使用 sync.Map 而不是通用地图。为这个堆栈溢出 question 提供的唯一答案启发了我这样做。但是,我不清楚这样做的正确语法。

对于我的第一次尝试,我使用了以下代码行:

var a_map = make(sync.Map[string] []int)

导致以下错误:

...syntax error: unexpected ], expecting expression

然后我尝试了:

 sync_map := new(sync.Map)
 var a_map = make(sync_map[string] []int)

导致同样的错误:

...syntax error: unexpected ], expecting expression

sync.Map 不是 Go map,所以你不能使用 a_map["key"] 语法。相反,它是一个 struct 方法,提供了通常的地图操作。使用它的语法是:

var m sync.Map
m.Store("example", []int{1, 2, 3})
fmt.Println(m.Load("example")) // [1 2 3] true

-- https://play.golang.org/p/7rbEG_x0mrC

根据您的并发源,您可能需要对每个键下的 []int 值进行类似的同步,sync.Map 不会给您。 sync.Map 仅提供 load/store 每个密钥的同步。如果是这样,请发表评论,我们会尽力帮助您。