From 7bc2a0b786759c7320f6dbd9d32ce3c86e4cc8d8 Mon Sep 17 00:00:00 2001 From: qmuntal Date: Mon, 24 Jul 2023 12:19:27 +0200 Subject: [PATCH] double checked locking --- statemachine.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/statemachine.go b/statemachine.go index 7d6dcb2..be3631f 100644 --- a/statemachine.go +++ b/statemachine.go @@ -309,10 +309,13 @@ func (sm *StateMachine) stateRepresentation(state State) *stateRepresentation { sr, ok := sm.stateConfig[state] sm.stateMutex.RUnlock() if !ok { - sr = newstateRepresentation(state) sm.stateMutex.Lock() - sm.stateConfig[state] = sr - sm.stateMutex.Unlock() + defer sm.stateMutex.Unlock() + // Check again, since another goroutine may have added it while we were waiting for the lock. + if sr, ok = sm.stateConfig[state]; !ok { + sr = newstateRepresentation(state) + sm.stateConfig[state] = sr + } } return sr }