From f23c8cd1407a04c75deb1c26860a9262d1924086 Mon Sep 17 00:00:00 2001 From: Martin Braun Date: Wed, 14 Feb 2018 15:33:09 -0800 Subject: mpm: Add lock_guard() function This allows sharing mutexes between C++ and Python, and uses the with statement to provide a locked-out context. --- mpm/python/usrp_mpm/mpmutils.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'mpm') diff --git a/mpm/python/usrp_mpm/mpmutils.py b/mpm/python/usrp_mpm/mpmutils.py index 151713988..a0716d1da 100644 --- a/mpm/python/usrp_mpm/mpmutils.py +++ b/mpm/python/usrp_mpm/mpmutils.py @@ -8,6 +8,7 @@ Miscellaneous utilities for MPM """ import time +from contextlib import contextmanager def poll_with_timeout(state_check, timeout_ms, interval_ms): """ @@ -163,3 +164,24 @@ def async_exec(parent, method_name, *args): while not awaitable_method(): time.sleep(0.1) +@contextmanager +def lock_guard(lockable): + """Context-based lock guard + + Use this in a with statement to lock out the following scope. Example: + >>> with lock_guard(some_mutex): + >>> thread_sensitive_function() + + In this snippet, we assume that some_mutex is a lockable object, and + implements lock() and unlock() member functions. Everything within the + with context will then be serialized. + + This is a useful mechanic for sharing mutexes between Python and C++. + + Arguments: + lockable -- Must have a .lock() and .unlock() method + """ + lockable.lock() + yield + lockable.unlock() + -- cgit v1.2.3