I recently encountered a problem about the sync.Map type when using the Go language: how to modify the data in it, especially in a concurrent environment. Here I would like to share my understanding and solution.
The sync.Map type in the Go language is a thread-safe Map that can be used in a concurrent environment. Its use is very simple. You can define a sync.Map variable through the following code:
var m sync.Map
Next, you can read and write elements through the Load and Store methods, for example:
m.Store("key1", "value1") v, ok := m.Load("key1")
What needs to be noted in this process is that the first parameter of the Store method is the key, the second parameter is the value, and the return value of the Load method has two, the first is the value, the second is a bool type The value indicating whether the key was found.
But, what should we do if we need to modify an element in sync.Map? The value cannot be modified directly through the subscript like the ordinary map type. Let’s take a look at what Go’s official documentation says about modifications:
It must not be copied after first use. To avoid ownership issues, values stored in the Map should not be modified.
The documentation states that the values in sync.Map should not be modified. This is because map is a reference type, and if we modify it, it may affect other coroutines, causing race conditions and data inconsistencies.
So, if we want to modify an existing key-value pair, what should we do?
In fact, we can use the Range method inside the sync.Map type to first read the elements that need to be modified through this method, and then rewrite a new value. The sample code is as follows:
m.Range(func(key, value interface{}) bool { if key == "key1" { m.Store(key, "newvalue") } return true })
Here we first traverse the entire Map through the Range method, and then determine whether the key that needs to be modified exists. If it exists, rewrite a new value through the Store method. It should be noted that if the Range method returns false, the traversal operation will stop.
Finally, we need to summarize:
Hope this article is helpful to you. If there is anything inappropriate, readers please give me some advice!
The above is the detailed content of golang sync map modification. For more information, please follow other related articles on the PHP Chinese website!