from threading import Lock class AtomicBoolean: ''' A {@code boolean} value that may be updated atomically. ''' def __init__(self, val:bool): ''' @param val the initial value ''' self._val = val self._lock = Lock() def get(self): ''' @return the current value ''' return self._val def compareAndSet(self, expectedValue:bool, newValue:bool)->bool: ''' Atomically sets the value to {@code newValue} if the current value {@code == expectedValue}, else do nothing, @param expectedValue the expected value @param newValue the new value @return {@code True} if successful. False return indicates that the actual value was not equal to the expected value. ''' with self._lock: if not self._val == expectedValue: return False self._val = newValue return True