Skip to content

Commit

Permalink
fix: avoid data race when setting memdb footprint hook (#621)
Browse files Browse the repository at this point in the history
Signed-off-by: ekexium <eke@fastmail.com>
  • Loading branch information
ekexium authored Nov 24, 2022
1 parent e9db9e6 commit 92f0a82
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 12 deletions.
5 changes: 3 additions & 2 deletions internal/unionstore/memdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import (
"math"
"reflect"
"sync"
"sync/atomic"
"unsafe"

tikverr "github.com/tikv/client-go/v2/error"
Expand Down Expand Up @@ -871,8 +872,8 @@ func (db *MemDB) SetMemoryFootprintChangeHook(hook func(uint64)) {
innerHook := func() {
hook(db.allocator.capacity + db.vlog.capacity)
}
db.allocator.memChangeHook = innerHook
db.vlog.memChangeHook = innerHook
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&db.allocator.memChangeHook)), unsafe.Pointer(&innerHook))
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&db.vlog.memChangeHook)), unsafe.Pointer(&innerHook))
}

// Mem returns the current memory footprint
Expand Down
4 changes: 2 additions & 2 deletions internal/unionstore/memdb_arena.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ type memdbArena struct {
// the total size of all blocks, also the approximate memory footprint of the arena.
capacity uint64
// when it enlarges or shrinks, call this function with the current memory footprint (in bytes)
memChangeHook func()
memChangeHook *func()
}

func (a *memdbArena) alloc(size int, align bool) (memdbArenaAddr, []byte) {
Expand Down Expand Up @@ -133,7 +133,7 @@ func (a *memdbArena) enlarge(allocSize, blockSize int) {

func (a *memdbArena) onMemChange() {
if a.memChangeHook != nil {
a.memChangeHook()
(*a.memChangeHook)()
}
}

Expand Down
5 changes: 0 additions & 5 deletions tikv/kv.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,11 +257,6 @@ func (s *KVStore) Begin(opts ...TxnOption) (txn *transaction.KVTxn, err error) {
opt(options)
}

defer func() {
if err == nil && txn != nil && options.MemoryFootprintChangeHook != nil {
txn.SetMemoryFootprintChangeHook(options.MemoryFootprintChangeHook)
}
}()
if options.TxnScope == "" {
options.TxnScope = oracle.GlobalTxnScope
}
Expand Down
5 changes: 2 additions & 3 deletions txnkv/transaction/txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,8 @@ type SchemaAmender interface {
// TxnOptions indicates the option when beginning a transaction.
// TxnOptions are set by the TxnOption values passed to Begin
type TxnOptions struct {
TxnScope string
StartTS *uint64
MemoryFootprintChangeHook func(uint64)
TxnScope string
StartTS *uint64
}

// KVTxn contains methods to interact with a TiKV transaction.
Expand Down

0 comments on commit 92f0a82

Please sign in to comment.