| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | import threading |
| 4 | |
| 5 | |
| 6 | class Counter: |
| 7 | def __init__(self, start: int = 0) -> None: |
| 8 | super().__init__() |
| 9 | |
| 10 | self.counter = start |
| 11 | |
| 12 | def __next__(self) -> int: |
| 13 | i = self.counter |
| 14 | self.counter += 1 |
| 15 | return i |
| 16 | |
| 17 | def reset(self) -> None: |
| 18 | self.counter = 0 |
| 19 | |
| 20 | |
| 21 | class AtomicCounter: |
| 22 | """An atomic, thread-safe counter.""" |
| 23 | |
| 24 | def __init__(self, initial: int = 0) -> None: |
| 25 | """Initialize a new atomic counter to given initial value.""" |
| 26 | super().__init__() |
| 27 | |
| 28 | self._value = initial |
| 29 | self._lock = threading.Lock() |
| 30 | |
| 31 | @property |
| 32 | def value(self) -> int: |
| 33 | return self._value |
| 34 | |
| 35 | def inc(self, num: int = 1) -> int: |
| 36 | """Atomically increment the counter by num and return the new value.""" |
| 37 | with self._lock: |
| 38 | self._value += num |
| 39 | return self._value |
| 40 | |
| 41 | def dec(self, num: int = 1) -> int: |
| 42 | """Atomically decrement the counter by num and return the new value.""" |
| 43 | with self._lock: |
| 44 | self._value -= num |
| 45 | return self._value |