Sorry, maybe I explain the code not clearly because of my poor English.
// global variable
var myMap map[int]string
...
// load regularly
go func() {
tmpMap := loadMap()
myMap = tmpMap
} ()
In this code, func loadMap() loads a configuration file into local variable tmpMap (memory).
Then using the configuration in tmpMap (memory) to update the old configuration in myMap (also memory).
myMap = tmpMap
I think you mean that I should use mutex like follows, and because the update is “myMap = tmp Map”, only using the memory, so this update process will not cost a long time and will not have a siginificant effect on the read process “v, ok := myMap[key]”.
m.lock()
myMap = tmpMap
m.unlock()
m.lock()
v, ok := myMap[key]
m.unlock()
In my view, this concurrent method is standard, of course right.
But on the other hand, I want to know what will happen if the mutex is removed, like the code in first floor.
As I known, the map (variable tmpMap and myMap) is a pointer in golang. So the operation “myMap = tmpMap” is the assignment of pointer. This operation only hand over the “actual map” they point to, during which the “actual map” is not modified.
In golang, the concurrent operation of a pointer variable will not cause panic. (while the concurrent operation of a map will cause panic, like this:
go func() {
myMap[key] = value
}
...
go func() {
v, ok := myMap[key]
}
)
Then, I want to discuss what will happen when we concurrently operate a pointer variable. In my opinion, if the pointer is written and read at the same time, the only problem may happen is that: the old address and the old data it points to may be read, and the write operation will be excuted currectly. In other words, write and read at the same time will only lead to the “dirty read”. And after a period of time, write and read at the same time will guarantee that the new data is written into pointer, so that read after a long time will return the new data.
So I think this process is also for map. Since I can bear the “dirty read”, it is unnecessary to add the mutex. But I still have some uncertainty, because I don’t have a deep understanding of the underlying principles of map and golang. Therefore, I create this topic and ask for help. As you said this concurrent operation cannot guarantee the above process, would you please tell me what problem this concurrent operation will lead to and why the problem will happen? Thanks a lot !