diff --git a/src/python/dm/common/utility/singleton.py b/src/python/dm/common/utility/singleton.py new file mode 100755 index 0000000000000000000000000000000000000000..8325b6bcaa859dc8c2cca8778a26e3143def395f --- /dev/null +++ b/src/python/dm/common/utility/singleton.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +class Singleton(object): + + __instance = None + + def __new__(cls, *args, **kwargs): + # Allow subclasses to create their own instances. + if cls.__instance is None or cls != type(cls.__instance): + instance = object.__new__(cls, *args, **kwargs) + cls.__instance = instance + instance.__init__(*args, **kwargs) + return cls.__instance + + @classmethod + def getInstance(cls, *args, **kwargs): + return cls.__new__(cls, *args, **kwargs) + + def __init__(self, *args, **kwargs): + # Only initialize once. + if Singleton.__instance is not None: + return + +#################################################################### +# Testing +if __name__ == '__main__': + s1 = Singleton.getInstance() + s2 = Singleton() + s3 = Singleton.getInstance() + s4 = Singleton() + print 'S1: ', s1 + print 'S2: ', s2 + print 'S3: ', s3 + print 'S4: ', s4 + class A(Singleton): + def __init__(self, x): + self.x = x + class B(Singleton): + def __init__(self, x): + self.x = x + class C(Singleton): + def __init__(self): + self.x = 14 + + a1 = A(3) + a2 = A(4) + print a1 + print a2 + print a2.x, a1.x + + b1 = B(6) + b2 = B(5) + print b1 + print b2 + print b2.x, b1.x + + c1 = C() + c2 = C() + print c1 + print c2 + print c2.x, c1.x diff --git a/src/python/dm/common/utility/threadSafeQueue.py b/src/python/dm/common/utility/threadSafeQueue.py new file mode 100755 index 0000000000000000000000000000000000000000..af7e99d31b92b24abed27e8d5b0bb7b98f8016cf --- /dev/null +++ b/src/python/dm/common/utility/threadSafeQueue.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +import threading + +class ThreadSafeQueue: + + def __init__(self): + self.lock = threading.RLock() + self.queue = [] + + def push(self, item): + self.lock.acquire() + try: + self.queue.insert(0,item) + finally: + self.lock.release() + + def pop(self): + # Return None if work queue is empty. + self.lock.acquire() + try: + item = None + if len(self.queue): + item = self.queue.pop() + return item + finally: + self.lock.release() + + def getLength(self): + return len(self.queue) + + def isEmpty(self): + return len(self.queue) == 0 + +#################################################################### +# Testing + +if __name__ == '__main__': + q = ThreadSafeQueue() + for i in range(0,10): + q.push(i) + print 'Added: ', i + + while not q.isEmpty(): + i = q.pop() + print 'Got: ', i + + +