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

Issue

I have the following line of code:

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

Part of my code, which is utilizing the a_map variable occasionally throws the following error:

fatal error: concurrent map read and map write

In an attempt to create a more robust solution, one that is free from such an error, I would like to use a sync.Map as opposed to a generic map. I was inspired to do so by the only answer provided to this stack overflow question. However, I am unclear as to the proper syntax for doing so.

For my first attempt I utilized the following line of code:

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

Which resulted in the following error:

...syntax error: unexpected ], expecting expression

Then I tried:

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

Which resulted in the same error:

...syntax error: unexpected ], expecting expression

Solution

sync.Map is not a Go map, and so you cannot using the a_map["key"] syntax with it. Rather, it is a struct with methods providing the usual map operations. The syntax for using it is:

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

Depending on the source of your concurrency, you may require similar synchronisation of the []int values under each key, which sync.Map will not give you. sync.Map only provides load/store synchronisation per key. Drop a comment if so, and we can try to help you out further.

Answered By – icio

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.