sync.Map (used in a concurrent environment Map)

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
  })
}

sync.Map provides no way to get the number of the map, when the alternative is to calculate the number of self-acquired sync.Map traversing, in order to ensure concurrent safety sync.Map some performance loss, and therefore in the case of non-concurrent use compared to use map sync .Map have better performance

Code output below:

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.

sync.Map provides no way to get the number of the map, when the alternative is to calculate the number of self-acquired sync.Map traversing, in order to ensure concurrent safety sync.Map some performance loss, and therefore in the case of non-concurrent use compared to use map sync .Map have better performance

 

Guess you like

Origin www.cnblogs.com/lurenq/p/12012117.html