Is assigning a map atomic in go

this is the example code:

var data map[string]string

func main() {

go func() {
	v := data["d"]
	fmt.Println(v)

}()
go func() {

	temp := make(map[string]string)
	temp["a"] = "a"
	data = temp
}()
 
}

one coroutine read the map,one coroutine modify the map, is the step: data = temp atomic?
What happens when the data type is array?

Hi, @SmallSmartMouse,

No, map assignment is not atomic. Also, your reassignment of the global data map with the temp one you created is not atomic.

If your idea is to initialize a map and then store it into a global variable where it will be considered read-only, you can do that with the sync/atomic package and some pointer hackery: https://play.golang.org/p/3UmzbTT0Pcl

If the global map is supposed to remain mutable, then you need to protect access with a mutex: https://play.golang.org/p/khh7W9NnHNi

Both of these solutions, I think, would be frowned upon by other Go developers, though. You should be using a higher-level abstraction to control access to the map, but I can’t provide a good example without knowing how you plan on using the map.

Hi, @skillian
I use the map as a local cache which one coroutine will read and the other coroutine will regularly
modify the map. If I take the address of the map,then I assign the address to the global map address pointer, is the assignment is atomic? Or in other word, Is assigning a pointer atomic in go?
this is example code:
var data *map[string]string
temp :=make(map[string]string)
data=&temp

Without a mutex or some other synchronization, this is not safe and could panic.

No. You have to use the sync/atomic package like I did in my previous post. Note that the x86 architecture does make loads and stores of pointers atomic, but to make your code work on other architectures like ARM, you have to use the sync/atomic package.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.