From 8080e71c0eb90858b4ff63855a3ca0cf879b2839 Mon Sep 17 00:00:00 2001 From: Sinisa Veseli <sveseli@aps.anl.gov> Date: Tue, 14 Apr 2015 14:56:56 +0000 Subject: [PATCH] added threading utility with decorator to help simplify code --- .../dm/common/utility/threadingUtility.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100755 src/python/dm/common/utility/threadingUtility.py diff --git a/src/python/dm/common/utility/threadingUtility.py b/src/python/dm/common/utility/threadingUtility.py new file mode 100755 index 00000000..98460ede --- /dev/null +++ b/src/python/dm/common/utility/threadingUtility.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + + +class ThreadingUtility: + + # Assumes class has instance lock initialized + @classmethod + def synchronize(cls, func): + def synchronized(*args, **kwargs): + im_self = args[0] + im_self.lock.acquire() + try: + result = func(*args, **kwargs) + return result + finally: + im_self.lock.release() + return synchronized + +####################################################################### +# Testing. +if __name__ == '__main__': + import threading + class A: + def __init__(self): + self.lock = threading.RLock() + + @ThreadingUtility.synchronize + def twoX(self, x): + print 'X=', x + return 2*x + + a = A() + t = a.twoX(3) + print 'Result: ', t + -- GitLab