Go并发编程-map
hash table的结构时日常开发中经常使用的,在go中内建了map的类型。本文介绍下在并发情况下的map
使用map的常见错误
-
map必须初始化后使用,否则会panic
// 直接使用忘记初始化 func main() { var m map[int]int m[100] = 100 } // 结构体中忘记初始化 type Counter struct { Website string Start time.Time PageCounters map[string]int } func main() { counter := Counter{ } counter.PageCounters["100"] = 100 } -
Map不支持并发读写,当有并发读写时会直接报错
func main() { m := make(map[int]int) go func() { for { m[1] = 1 } }() go func() { for { _ = m[2] } }() select { } }
线程安全的map类型
type RWMap struct {
sync.RWMutex
m map[int]int
}
func (r *RWMap) Get(key int) (int, bool) {
r.RLock()
defer r.RUnlock()
value, exist := r.m[key]
return value, exist
}
func (r *RWMap) Set(key, value int) {
r.Lock()
defer r.Unlock()
r.m[key] = value
}
更高效的并发map-分片加锁
锁是性能下降的万恶之源,想要提高性能就要减少锁的竞争。可以通过分片的方式减少map的竞争锁从而提高性能。推荐使用 concurrent-map
type ConcurrentMap []*ConcurrentMapShard
const SHARD_COUNT = 32
type ConcurrentMapShard struct {
sync.RWMutex
items map[string]interface{}
}
func New() ConcurrentMap {
m := make(ConcurrentMap, SHARD_COUNT)
for i := 0; i < SHARD_COUNT; i++ {
m[i] = &ConcurrentMapShard{items: make(map[string]interface{})}
}
return m
}
func (m ConcurrentMap) GetShard(key string) *ConcurrentMapShard {
return m[uint(fnv32(key))%uint(SHARD_COUNT)]
}
func (m ConcurrentMap) Set(key string, value interface{}) {
shard := m.GetShard(key)
shard.Lock()
defer shard.Unlock()
shard.items[key] = value
}
func (m ConcurrentMap) Get(key string) (interface{}, bool) {
shard := m.GetShard(key)
shard.RLock()
defer shard.RUnlock()
value, exist := shard.items[key]
return value, exist
}
func fnv32(key string) uint32 {
hash := uint32(2166136261)
const prime32 = uint32(16777619)
for i := 0; i < len(key); i++ {
hash *= prime32
hash ^= uint32(key[i])
}
return hash
}
go 内置的sync.Map
Go 1.9增加了一个线程安全的sync.Map,在特殊的场景中他的性能比RWMutex+map的方式好的多。场景:
-
只会增长的缓存系统,一个key只写入一次而被读很多次
-
多个goroutine为不相交的键集读、写和重写键值对
定义很模糊,其实这种方式的场景要经过性能评测再决定是否使用。实际中他的使用场景还是比较少的。
看实现
// sync.Map使用了冗余的字段,其中read字段是不需要加锁的,并且优先从read中读取、更新、删除。
// miss次数多了之后,将dirty数据提升为read并把dirty设置为nil.
// read和dirty指向同一个指针,read修改后dirty自动会修改
type Map struct {
mu Mutex
read atomic.Value // readOnly
dirty map[interface{}]*entry
misses int
}
// store同时实现了新增和修改。当read中存在时,就是更新的read不会用到锁,直接cas赋值,性能比较好,但是如果read中没有则会使用到锁,性能就会下降。Load和Delete大概的思路一致。只要都是操作read,性能就会非常好
func (m *Map) Store(key, value interface{}) {
read, _ := m.read.Load().(readOnly)
if e, ok := read.m[key]; ok && e.tryStore(&value) {
return
}
m.mu.Lock()
read, _ = m.read.Load().(readOnly)
if e, ok := read.m[key]; ok {
if e.unexpungeLocked() {
m.dirty[key] = e
}
e.storeLocked(&value)
} else if e, ok := m.dirty[key]; ok {
e.storeLocked(&value)
} else {
if !read.amended {
m.dirtyLocked()
m.read.Store(readOnly{m: read.m, amended: true})
}
m.dirty[key] = newEntry(value)
}
m.mu.Unlock()
}
本文探讨了Go语言中Map的基本使用及并发场景下的注意事项,包括常见的错误、线程安全的实现方式以及如何通过分片加锁提高性能。特别介绍了Go 1.9引入的sync.Map及其适用场景。

1526

被折叠的 条评论
为什么被折叠?



