utils: protect obj_id() and obj_count() with a lock

This commit is contained in:
Aleix Conchillo Flaqué
2025-01-29 23:06:12 -08:00
parent 41d60a14cc
commit 10716e8ec1

View File

@@ -6,9 +6,12 @@
import collections
import itertools
import threading
_COUNTS = collections.defaultdict(itertools.count)
_COUNTS_LOCK = threading.Lock()
_ID = itertools.count()
_ID_LOCK = threading.Lock()
def obj_id() -> int:
@@ -21,7 +24,8 @@ def obj_id() -> int:
>>> obj_id()
2
"""
return next(_ID)
with _ID_LOCK:
return next(_ID)
def obj_count(obj) -> int:
@@ -35,4 +39,5 @@ def obj_count(obj) -> int:
>>> obj_count(new_type())
0
"""
return next(_COUNTS[obj.__class__.__name__])
with _COUNTS_LOCK:
return next(_COUNTS[obj.__class__.__name__])