sync.Map has the following features:
When required concurrent read and write, the general practice is locked, but this performance is not high, Go language provides a high efficiency of concurrent secure sync.Map in version 1.9, different sync.Map and map, not to providing native language form, but under special sync packet structure.
-
Without initialization, you can direct statement.
-
sync.Map not use the map and other values and approach to setting operation, but the use of the method sync.Map call, Store representation storage, Load retrieves, Delete means to delete.
-
Range using a callback function with a traverse, traversing the inside out return values callback function, the return value of the callback function Range parameter when the need to continue iterating, returns true, iterating terminated, return false.
Concurrent secure sync.Map demo code is as follows:
main Package Import ( "FMT" "Sync" ) FUNC main () { var SCENE sync.Map // save the key-value pair sync.Map scene.Store ( "Greece", 97) scene.Store ( "London", 100) scene.Store ( "Egypt", 200 is) // key values from sync.Map according fmt.Println (scene.Load ( "London")) // delete the corresponding key according to the key value scene.Delete ( "London") // loop through all key-value pairs sync.Map scene.Range (FUNC (K, V interface {}) {BOOL fmt.Println ( "the iterate:", K,v) return true }) }
100 true
iterate: egypt 200
iterate: greece 97
Code as follows:
-
Line 10, the statement scene, type sync.Map, attention, sync.Map not use make to create.
-
13 to line 15, to a series of key-value pairs stored in sync.Map, sync.Map key and value type interface {} to be saved.
-
Line 18 provides a key to scene.Load sync.Map after () method to query returns a value corresponding to the key.
-
Line 21, sync.Map can be used to specify the Delete key to delete the corresponding key.
-
Line 24, the Range () method may traverse sync.Map, a need to provide a traverse anonymous function, parameter k, v, type interface {}, each time the Range () while traversing an element, the function will be called anonymous results are returned.