Line data Source code
1 : // Copyright 2024 Accenture. 2 : 3 : /** 4 : * \ingroup async 5 : */ 6 : #pragma once 7 : 8 : #include "interrupts/suspendResumeAllInterrupts.h" 9 : 10 : namespace async 11 : { 12 : /** 13 : * A synchronization mechanism that blocks threads from accessing a resource. 14 : * 15 : * The `ModifiableLock` class ensures mutual exclusion, 16 : * allowing only one thread to access a protected 17 : * resource or function at a time. When a thread acquires the lock, 18 : * any other thread attempting to acquire it is blocked until the lock is released. 19 : * The lock can be acquired either in the constructor or on demand using the `lock` function. 20 : * Similarly, the lock can be released either in the destructor or on demand using the `unlock` 21 : * function. 22 : */ 23 : class ModifiableLock final 24 : { 25 : public: 26 : ModifiableLock(); 27 : ~ModifiableLock(); 28 : 29 : void unlock(); 30 : void lock(); 31 : 32 : private: 33 : ::OldIntEnabledStatusValueType _oldIntEnabledStatusValue; 34 : bool _isLocked; 35 : }; 36 : 37 : /** 38 : * Inline implementations. 39 : */ 40 3 : inline ModifiableLock::ModifiableLock() 41 3 : : _oldIntEnabledStatusValue(::getOldIntEnabledStatusValueAndSuspendAllInterrupts()), _isLocked(true) 42 : {} 43 : 44 3 : inline ModifiableLock::~ModifiableLock() 45 : { 46 2 : if (_isLocked) 47 : { 48 2 : ::resumeAllInterrupts(_oldIntEnabledStatusValue); 49 : } 50 : } 51 : 52 3 : inline void ModifiableLock::unlock() 53 : { 54 3 : if (_isLocked) 55 : { 56 2 : ::resumeAllInterrupts(_oldIntEnabledStatusValue); 57 2 : _isLocked = false; 58 : } 59 3 : } 60 : 61 2 : inline void ModifiableLock::lock() 62 : { 63 2 : if (!_isLocked) 64 : { 65 1 : _oldIntEnabledStatusValue = ::getOldIntEnabledStatusValueAndSuspendAllInterrupts(); 66 1 : _isLocked = true; 67 : } 68 2 : } 69 : 70 : } // namespace async