mirror of
https://opendev.org/x/pyghmi
synced 2025-01-15 04:07:48 +00:00
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
This commit is contained in:
parent
756ebdbffb
commit
3e6ca2dcb1
@ -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()
|
||||
|
Loading…
x
Reference in New Issue
Block a user