简介
Sync包下的map很像是Go的map[interface{}]interface{},但是对于普通的map来说,sync.Map可以保证在多个goroutine的并发使用是安全的,无需额外添加锁来进行控制
方法
func (m *Map) Store(key, value interface{})
将一个key,value存入map中
func main() {
var syncMap sync.Map
// Store: func (m *Map) Store(key, value interface{})
syncMap.Store("golang", "map")
value, ok := syncMap.Load("golang")
if !ok {
fmt.Println("The key not exist")
return
}
fmt.Println(value)
}
func (m *Map) Delete(key interface{})
将一个key从map中删除
func main() {
var syncMap sync.Map
// Store: func (m *Map) Store(key, value interface{})
syncMap.Store("golang", "map")
// Delete: func (m *Map) Delete(key interface{})
syncMap.Delete("golang")
value, ok = syncMap.Load("golang")
if !ok {
fmt.Println("The key not exist")
return
}
fmt.Println(value)
}
func (m *Map) Load(key interface{}) (value interface{}, ok bool)
从map中获取一个Key
func (m *Map) LoadAndDelete(key interface{}) (value interface{}, loaded bool)
从map中获取一个key,并且将key删除,如果key存在那么loaded会返回true,并且value就是map中存的值,如果key不存在那么loaded会返回一个false,并且value为nil
func main() {
var syncMap sync.Map
// LoadAndDelete: func (m *Map) LoadAndDelete(key interface{}) (value interface{}, loaded bool)
syncMap.Store("golang", "map")
value, ok := syncMap.LoadAndDelete("golang")
fmt.Printf("values is %v,is loaded %v \n", value, ok)
value, ok = syncMap.LoadAndDelete("golang")
fmt.Printf("values is %v,is loaded %v \n", value, ok)
}
func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)
从map中加载一个key,如果key不存在,那么就会将value存放在key中,返回value,loaded为false,如果key存在则返回value(key原有的值),loaded为true,不会更新传入的value,如果想更新用Store
func main() {
var syncMap sync.Map
// LoadOrStore: func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)
actual, loaded := syncMap.LoadOrStore("golang", "wzy")
fmt.Printf("actual %v,is loaded %v \n", actual, loaded)
actual, loaded = syncMap.LoadOrStore("golang", "test")
fmt.Printf("actual %v,is loaded %v \n", actual, loaded)
value, ok = syncMap.Load("golang")
fmt.Printf("values is %v,is loaded %v \n", value, ok)
}
//actual wzy,is loaded false
//actual wzy,is loaded true
//values is wzy,is loaded true
func (m *Map) Range(f func(key, value interface{}) bool)
迭代出map中的key,value,如果回调函数中返回false,那么就会停止迭代,如果返回true,那么就会继续迭代
func main(){
var syncMap sync.Map
syncMap.Store("golang", "wzy")
syncMap.Store("golang2", "zhao")
syncMap.Range(func(key, value interface{}) bool {
fmt.Printf("Key: %v - Value: %v\n", key, value)
return true
})
}