Skip to content

Commit 7037ecb

Browse files
committed
fsm: add helper to acquire lock
This commit adds a helper function to the fsm to acquire the fsm lock and safely acces members.
1 parent 6a70166 commit 7037ecb

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

fsm/fsm.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,27 @@ func (s *StateMachine) SendEvent(ctx context.Context, event EventType,
269269
}
270270
}
271271

272+
// GetStateMachineLock locks the state machine mutex and returns a function that
273+
// unlocks it.
274+
func (s *StateMachine) GetStateMachineLock(ctx context.Context) (func(), error) {
275+
gotLock := make(chan struct{})
276+
// Try to get the lock.
277+
go func() {
278+
s.mutex.Lock()
279+
close(gotLock)
280+
}()
281+
282+
for {
283+
select {
284+
case <-ctx.Done():
285+
return nil, errors.New("context canceled")
286+
287+
case <-gotLock:
288+
return s.mutex.Unlock, nil
289+
}
290+
}
291+
}
292+
272293
// RegisterObserver registers an observer with the state machine.
273294
func (s *StateMachine) RegisterObserver(observer Observer) {
274295
s.observerMutex.Lock()

0 commit comments

Comments
 (0)