golang 中map并发读写操作

来源:互联网 发布:php实现字符串反转 编辑:程序博客网 时间:2024/05/25 18:10

go中map并发使用是不安全的,当你使用goroutine同时对一个map进行读写操作时,不确定会发生什么(由于读写执行顺序不确定造成的).针对这种情况,我们要添加读写锁对sync.RWMutex其进行同步.

var counter = struct{    sync.RWMutex    m map[string]int}{m: make(map[string]int)}

从counter读取数据,使用读锁

counter.RLock()n := counter.m["some_key"]counter.RUnlock()fmt.Println("some_key:", n)

向counter写数据,使用写锁

counter.Lock()counter.m["some_key"]++counter.Unlock()

参考:http://blog.golang.org/go-maps-in-action

0 0
原创粉丝点击