Map with concurrent access

前端 未结 6 1361

When you use a map in a program with concurrent access, is there any need to use a mutex in functions to read values?

6条回答
  •  天命终不由人
    2020-11-29 01:50

    You could use concurrent-map to handle the concurrency pains for you.

    // Create a new map.
    map := cmap.NewConcurrentMap()
    
    // Add item to map, adds "bar" under key "foo"
    map.Add("foo", "bar")
    
    // Retrieve item from map.
    tmp, ok := map.Get("foo")
    
    // Checks if item exists
    if ok == true {
        // Map stores items as interface{}, hence we'll have to cast.
        bar := tmp.(string)
    }
    
    // Removes item under key "foo"
    map.Remove("foo")
    

提交回复
热议问题