Line | |
---|
1 | from threading import Lock
|
---|
2 |
|
---|
3 | class 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.