Commit 2550bca6 authored by Antoine Millet's avatar Antoine Millet
Browse files

Added AcquiresAllOrNone class in utils.

parent 05c4197d
Loading
Loading
Loading
Loading
+27 −0
Original line number Diff line number Diff line
@@ -5,6 +5,8 @@
Some helpers used by cc-server.
'''

from threading import Lock

class Acquires(object):

    '''
@@ -34,3 +36,28 @@ class Acquires(object):
    def __exit__(self, exc_type, exc_value, traceback):
        for lock in self._locks:
            lock.release()


class AcquiresAllOrNone(Acquires):

    '''
    Class that extend Acquires to allow to release all lock if one of them
    is not free.
    '''

    # Global acquire lock:
    acquirelock = Lock()

    def __enter__(self):
        while True:
            with self.acquirelock:
                acquired = []
                for lock in self._locks:
                    if not lock.acquire(False):
                        for lock_acquired in acquired:
                            lock_acquired.release()
                        break
                    else:
                        acquired.append(lock)
                else:
                    break