golang sync.Map 使用

自1.9版本以后提供了sync.Map,支持多线程并发读写,比之前的加锁map性能要好一点。

提供一下几个方法:

type Map
    //删除指定key
    func (m *Map) Delete(key interface{})
    
    //查询指定key
    func (m *Map) Load(key interface{}) (value interface{}, ok bool)

    //查询,查不到则追加
    func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)

    //遍历map
    func (m *Map) Range(f func(key, value interface{}) bool)

    //添加
    func (m *Map) Store(key, value interface{})

用例:

// main.go
package main

import (
	"fmt"
	"sync"
)

type Class struct {
	Students sync.Map
}

func handler(key, value interface{}) bool {
	fmt.Printf("Name :%s %s\n", key, value)
	return true
}

func main() {

	class := &Class{}

	//存储值
	class.Students.Store("Zhao", "class 1")
	class.Students.Store("Qian", "class 2")
	class.Students.Store("Sun", "class 3")

	//遍历,传入一个函数,遍历的时候函数返回false则停止遍历
	class.Students.Range(handler)

	//查询
	if _, ok := class.Students.Load("Li"); !ok {
		fmt.Println("-->Li not found")
	}

	//查询或者追加
	_, loaded := class.Students.LoadOrStore("Li", "class 4")
	if loaded {
		fmt.Println("-->Load Li success")
	} else {
		fmt.Println("-->Store Li success")
	}

	//删除
	class.Students.Delete("Sun")
	fmt.Println("-->Delete Sun success")

	//遍历
	class.Students.Range(handler)

}

参考文档:

1. https://golang.org/pkg/sync/#Map

猜你喜欢

转载自blog.csdn.net/fuyuande/article/details/89416433