博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
golang 中map并发读写操作
阅读量:6996 次
发布时间:2019-06-27

本文共 416 字,大约阅读时间需要 1 分钟。

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()
参考:

转载于:https://www.cnblogs.com/msnsj/p/4242583.html

你可能感兴趣的文章