47 lines
1.0 KiB
Python
47 lines
1.0 KiB
Python
from functools import wraps
|
|
from threading import RLock
|
|
from typing import Optional
|
|
|
|
__all__ = [
|
|
'synchronized', 'Synchronized'
|
|
]
|
|
|
|
|
|
def synchronized(f):
|
|
if f.__doc__ is not None:
|
|
f.__doc__ = "**(synchronized)** " + f.__doc__
|
|
else:
|
|
f.__doc__ = "**(synchronized)**"
|
|
|
|
@wraps(f)
|
|
def _synchronized(self, *argv, **karg):
|
|
if hasattr(self, '__enter__'):
|
|
with self:
|
|
return f(self, *argv, **karg)
|
|
else:
|
|
return f(self, *argv, **karg)
|
|
|
|
return _synchronized
|
|
|
|
|
|
class Synchronized:
|
|
__slots__ = ('__lock',)
|
|
|
|
def __init__(self):
|
|
self.__lock = RLock()
|
|
|
|
def __enter__(self):
|
|
self.__lock.acquire()
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
self.__lock.release()
|
|
|
|
def lock_acquire(self, timeout: Optional[int] = None) -> bool:
|
|
if timeout is None:
|
|
return self.__lock.acquire(blocking=False)
|
|
else:
|
|
return self.__lock.acquire(timeout=timeout)
|
|
|
|
def lock_release(self):
|
|
self.__lock.release()
|