Skip to content

Commit

Permalink
memdb: fix data race between mutators and UnionScan (#20365)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zejun Li authored Oct 9, 2020
1 parent d1b10d4 commit 2f98a29
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions kv/memdb/arena.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package memdb

import (
"math"
"sync"
"unsafe"
)

Expand Down Expand Up @@ -42,6 +43,7 @@ const (
)

type arena struct {
sync.Mutex
blockSize int
blocks []arenaBlock
}
Expand All @@ -57,17 +59,20 @@ func newArenaLocator() *arena {
}

func (a *arena) snapshot() arenaSnapshot {
a.Lock()
snap := arenaSnapshot{
blockSize: a.blockSize,
blocks: len(a.blocks),
}
if len(a.blocks) > 0 {
snap.offsetInBlock = a.blocks[len(a.blocks)-1].length
}
a.Unlock()
return snap
}

func (a *arena) revert(snap arenaSnapshot) {
a.Lock()
for i := snap.blocks; i < len(a.blocks); i++ {
a.blocks[i] = arenaBlock{}
}
Expand All @@ -76,6 +81,7 @@ func (a *arena) revert(snap arenaSnapshot) {
a.blocks[len(a.blocks)-1].length = snap.offsetInBlock
}
a.blockSize = snap.blockSize
a.Unlock()
}

func (a *arena) newNode(key []byte, v []byte, height int) (*node, arenaAddr) {
Expand All @@ -92,7 +98,10 @@ func (a *arena) newNode(key []byte, v []byte, height int) (*node, arenaAddr) {
}

func (a *arena) getFrom(addr arenaAddr) []byte {
return a.blocks[addr.blockIdx-1].getFrom(addr.blockOffset)
a.Lock()
block := &a.blocks[addr.blockIdx-1]
a.Unlock()
return block.getFrom(addr.blockOffset)
}

func (a *arena) alloc(size int) (arenaAddr, []byte) {
Expand Down Expand Up @@ -122,7 +131,11 @@ func (a *arena) enlarge(allocSize, blockSize int) {
if a.blockSize > maxBlockSize {
a.blockSize = maxBlockSize
}
a.blocks = append(a.blocks, newArenaBlock(a.blockSize))
block := newArenaBlock(a.blockSize)

a.Lock()
a.blocks = append(a.blocks, block)
a.Unlock()
}

func (a *arena) allocInLastBlock(size int) (arenaAddr, []byte) {
Expand Down

0 comments on commit 2f98a29

Please sign in to comment.