Skip to content

Commit

Permalink
opt: Prevents false sharing by padding mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
0-haha committed Apr 7, 2023
1 parent 9d2f4df commit 199f16b
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,21 @@ import (
"github.com/zeebo/xxh3"
)

type mutex struct {
sync.RWMutex
// Prevents false sharing on widespread platforms with
// 128 mod (cache line size) = 0 .
pad [128 - unsafe.Sizeof(sync.RWMutex{})%128]byte
}

// Map is a hashmap. Like map[string]interface{}, but sharded and thread-safe.
type Map[K comparable, V any] struct {
init sync.Once
cap int
shards int
shardIDMax uint64
seed uint64
mus []sync.RWMutex
mus []mutex
maps []*mapShard[K, V]
kstr bool
ksize int
Expand Down Expand Up @@ -50,9 +57,9 @@ func (m *Map[K, V]) Init() {
}
m.shardIDMax = uint64(m.shards - 1)
scap := m.cap / m.shards
m.mus = make([]sync.RWMutex, m.shards)
m.mus = make([]mutex, m.shards)
m.maps = make([]*mapShard[K, V], m.shards)
for i := 0; i < len(m.maps); i++ {
for i := 0; i < m.shards; i++ {
m.maps[i] = newShard[K, V](scap)
}
})
Expand Down

0 comments on commit 199f16b

Please sign in to comment.