2021-01-18 19:29:03 +01:00
|
|
|
from typing import Callable
|
|
|
|
|
2022-05-24 22:14:25 -07:00
|
|
|
from ray.rllib.utils.annotations import DeveloperAPI
|
2021-01-18 19:29:03 +01:00
|
|
|
|
2022-05-24 22:14:25 -07:00
|
|
|
|
|
|
|
@DeveloperAPI
|
2021-11-01 21:46:02 +01:00
|
|
|
def with_lock(func: Callable) -> Callable:
|
2021-01-18 19:29:03 +01:00
|
|
|
"""Use as decorator (@withlock) around object methods that need locking.
|
|
|
|
|
|
|
|
Note: The object must have a self._lock = threading.Lock() property.
|
|
|
|
Locking thus works on the object level (no two locked methods of the same
|
|
|
|
object can be called asynchronously).
|
|
|
|
|
|
|
|
Args:
|
2021-11-01 21:46:02 +01:00
|
|
|
func: The function to decorate/wrap.
|
2021-01-18 19:29:03 +01:00
|
|
|
|
|
|
|
Returns:
|
2021-11-01 21:46:02 +01:00
|
|
|
The wrapped (object-level locked) function.
|
2021-01-18 19:29:03 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
def wrapper(self, *a, **k):
|
|
|
|
try:
|
|
|
|
with self._lock:
|
|
|
|
return func(self, *a, **k)
|
2021-02-25 12:18:11 +01:00
|
|
|
except AttributeError as e:
|
|
|
|
if "has no attribute '_lock'" in e.args[0]:
|
|
|
|
raise AttributeError(
|
|
|
|
"Object {} must have a `self._lock` property (assigned "
|
|
|
|
"to a threading.RLock() object in its "
|
|
|
|
"constructor)!".format(self)
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2021-02-25 12:18:11 +01:00
|
|
|
raise e
|
2021-01-18 19:29:03 +01:00
|
|
|
|
|
|
|
return wrapper
|