Skip to content

Commit 6c3d446

Browse files
JkLondonJkLondon
andauthored
Upd nst flag (#182)
* Add platform-specific thread ID retrieval and enforce strict thread checks * fix of win * Add strict thread checking mode to ensure thread safety in transactions * Refactor StrictThreadCheck to strictThreadCheck for naming consistency --------- Co-authored-by: JkLondon <ilya@mikheev.fun>
1 parent cf52800 commit 6c3d446

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

mdbx/env.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ type Env struct {
138138
// closeLock is used to allow the Txn finalizer to check if the Env has
139139
// been closed, so that it may know if it must abort.
140140
closeLock sync.RWMutex
141+
142+
strictThreadCheck bool
141143
}
142144

143145
// NewEnv allocates and initializes a new Env.
@@ -164,6 +166,11 @@ func (env *Env) Open(path string, flags uint, mode os.FileMode) error {
164166
}
165167
func (env *Env) Label() Label { return env.label }
166168

169+
// SetStrictThreadMode in this mode mdbx panics when tx opening and closing are happening in different threads
170+
func (env *Env) SetStrictThreadMode(mode bool) {
171+
env.strictThreadCheck = mode
172+
}
173+
167174
var errNotOpen = errors.New("enivornment is not open")
168175

169176
/* TODO: fix error: cannot convert *mf (variable of type _Ctype_HANDLE) to type uintptr

mdbx/txn.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,9 @@ func beginTxn(env *Env, parent *Txn, flags uint) (*Txn, error) {
9090
readonly: flags&Readonly != 0,
9191
env: env,
9292
}
93-
txn.tid = threads.CurrentThreadID()
93+
if env.strictThreadCheck {
94+
txn.tid = threads.CurrentThreadID()
95+
}
9496

9597
var ptxn *C.MDBX_txn
9698
if parent != nil {
@@ -304,6 +306,9 @@ func (txn *Txn) Abort() {
304306
}
305307

306308
func (txn *Txn) strictThreadCheck() {
309+
if !txn.env.strictThreadCheck {
310+
return
311+
}
307312
currentThread := threads.CurrentThreadID()
308313
if currentThread != txn.tid {
309314
msg := fmt.Sprintf("thread mismatch. not allowed current %d, open in %d", currentThread, txn.tid)
@@ -319,7 +324,9 @@ func (txn *Txn) abort() {
319324
// Get a read-lock on the environment so we can abort txn if needed.
320325
// txn.env **should** terminate all readers otherwise when it closes.
321326
txn.env.closeLock.RLock()
322-
txn.strictThreadCheck()
327+
if txn.env.strictThreadCheck {
328+
txn.strictThreadCheck()
329+
}
323330
if txn.env._env != nil {
324331
C.mdbx_txn_abort(txn._txn)
325332
}

0 commit comments

Comments
 (0)