source: utilitiespy/tudelft/utilities/tools/atomic.py@ 1323

Last change on this file since 1323 was 1306, checked in by wouter, 2 weeks ago

#407 added AtomicBoolean, bump 1.1.3

File size: 1004 bytes
Line 
1from threading import Lock
2
3class AtomicBoolean:
4 '''
5 A {@code boolean} value that may be updated atomically.
6 '''
7 def __init__(self, val:bool):
8 '''
9 @param val the initial value
10 '''
11 self._val = val
12 self._lock = Lock()
13
14 def get(self):
15 '''
16 @return the current value
17 '''
18 return self._val
19
20 def compareAndSet(self, expectedValue:bool, newValue:bool)->bool:
21 '''
22 Atomically sets the value to {@code newValue}
23 if the current value {@code == expectedValue}, else do nothing,
24 @param expectedValue the expected value
25 @param newValue the new value
26 @return {@code True} if successful. False return indicates that
27 the actual value was not equal to the expected value.
28 '''
29 with self._lock:
30 if not self._val == expectedValue:
31 return False
32 self._val = newValue
33 return True
34
35
Note: See TracBrowser for help on using the repository browser.