testutil: add AtomicCounter() as a threadsafe counter
The existing code in the reqs counting is not really thread safe, this commit fixes that.
This commit is contained in:
parent
b90a5027dc
commit
b9b296a7e5
4 changed files with 39 additions and 8 deletions
29
osbuild/testutil/atomic.py
Normal file
29
osbuild/testutil/atomic.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/python3
|
||||
"""
|
||||
thread/atomic related utilities
|
||||
"""
|
||||
import threading
|
||||
|
||||
|
||||
class AtomicCounter:
|
||||
""" A thread-safe counter """
|
||||
|
||||
def __init__(self, count: int = 0) -> None:
|
||||
self._count = count
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def inc(self) -> None:
|
||||
""" increase the count """
|
||||
with self._lock:
|
||||
self._count += 1
|
||||
|
||||
def dec(self) -> None:
|
||||
""" decrease the count """
|
||||
with self._lock:
|
||||
self._count -= 1
|
||||
|
||||
@property
|
||||
def count(self) -> int:
|
||||
""" get the current count """
|
||||
with self._lock:
|
||||
return self._count
|
||||
Loading…
Add table
Add a link
Reference in a new issue