On Wed, Oct 24, 2012 at 2:19 PM, Ian Kelly <ian.g.ke...@gmail.com> wrote: > I used a PriorityQueue and Conditions to get rid of the ugly while True loop.
Same things, but with Events instead of Conditions. This is just a bit more readable. The PriorityQueue is also probably unnecessary, since it's always accessed with the mutex held. A heapq would be fine. import threading import Queue class PriorityLock(object): def __init__(self): self._is_available = True self._mutex = threading.Lock() self._waiter_queue = Queue.PriorityQueue() def acquire(self, priority=0): self._mutex.acquire() # First, just check the lock. if self._is_available: self._is_available = False self._mutex.release() return True event = threading.Event() self._waiter_queue.put((priority, event)) self._mutex.release() event.wait() # When the event is triggered, we have the lock. return True def release(self): self._mutex.acquire() # Notify the next thread in line, if any. try: _, event = self._waiter_queue.get_nowait() except Queue.Empty: self._is_available = True else: event.set() self._mutex.release() -- http://mail.python.org/mailman/listinfo/python-list