Commit 5485f34b authored by Antoine Millet's avatar Antoine Millet
Browse files

Added Acquires class in the new utils module.

parent cfda64a5
Loading
Loading
Loading
Loading

ccserver/utils.py

0 → 100644
+36 −0
Original line number Diff line number Diff line
#!/usr/bin/env python
#coding=utf8

'''
Some helpers used by cc-server.
'''

class Acquires(object):

    '''
    Context manager used to acquire more than one lock at once. It works rely
    on the fact that if locks are always acquired in the same order, we can't
    enter in a deadlock situation.

    Usage is very simple:

    >>> a = Lock()
    >>> b = Lock()
    >>> with Acquires(b, a):
    ...     print 'locked'
    ...

    .. seealso::
        http://dabeaz.blogspot.com/2009/11/python-thread-deadlock-avoidance_20.html
    '''

    def __init__(self, *locks):
        self._locks = sorted(locks, key=lambda x: id(x))

    def __enter__(self):
        for lock in self._locks:
            lock.acquire()

    def __exit__(self, exc_type, exc_value, traceback):
        for lock in self._locks:
            lock.release()