Skip to content

Commit

Permalink
fix: initialize mutex before using (#233)
Browse files Browse the repository at this point in the history
  • Loading branch information
MuZhou233 authored Apr 2, 2024
1 parent 4e7c05a commit 8e4fe6d
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"runtime"
"strings"
"sync"
"sync/atomic"

"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
Expand Down Expand Up @@ -83,6 +84,7 @@ type Adapter struct {
db *gorm.DB
isFiltered bool
transactionMu *sync.Mutex
muInitialize atomic.Bool
}

// finalizer is the destructor for Adapter.
Expand Down Expand Up @@ -668,6 +670,16 @@ func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error

// Transaction perform a set of operations within a transaction
func (a *Adapter) Transaction(e casbin.IEnforcer, fc func(casbin.IEnforcer) error, opts ...*sql.TxOptions) error {
// ensure the transactionMu is initialized
if a.transactionMu == nil {
for a.muInitialize.CompareAndSwap(false, true) {
if a.transactionMu == nil {
a.transactionMu = &sync.Mutex{}
}
a.muInitialize.Store(false)
}
}
// lock the transactionMu to ensure the transaction is thread-safe
a.transactionMu.Lock()
defer a.transactionMu.Unlock()
var err error
Expand Down

0 comments on commit 8e4fe6d

Please sign in to comment.