From 3e6ca2dcb1d03387a3688034e2ede61734b5d2bc Mon Sep 17 00:00:00 2001 From: Akira Yoshiyama Date: Wed, 12 Jul 2017 10:59:59 +0900 Subject: [PATCH] Implement util.protect() lock manager protect() handles exclusive locks. It can be used as a context manager and as a decorator. Multi-thread applications like virshbmc require exclusive locks to protect list operations and references. Usage: import threading from pyghmi.ipmi.private import util LOCK = threading.Lock() @util.protect(LOCK) def foo(): ... or def foo(): with util.protect(LOCK): ... Change-Id: I96eb1fac17a519b4e864731f4fa0285ccc2edb08 --- pyghmi/ipmi/private/util.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/pyghmi/ipmi/private/util.py b/pyghmi/ipmi/private/util.py index ab4bc62f..bb177ee3 100644 --- a/pyghmi/ipmi/private/util.py +++ b/pyghmi/ipmi/private/util.py @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. import ctypes +import functools import os import socket import struct @@ -107,3 +108,25 @@ def _monotonic_time(): if wintime: return wintime() / 1000.0 return os.times()[4] + + +class protect(object): + + def __init__(self, lock): + self.lock = lock + + def __call__(self, func): + @functools.wraps(func) + def _wrapper(*args, **kwargs): + self.lock.acquire() + try: + return func(*args, **kwargs) + finally: + self.lock.release() + return _wrapper + + def __enter__(self): + self.lock.acquire() + + def __exit__(self, exc_type, exc_value, traceback): + self.lock.release()