A lock that prioritizes acquire()s?
Ian Kelly
ian.g.kelly at gmail.com
Wed Oct 24 17:00:09 EDT 2012
More information about the Python-list mailing list
Wed Oct 24 17:00:09 EDT 2012
- Previous message (by thread): A lock that prioritizes acquire()s?
- Next message (by thread): A lock that prioritizes acquire()s?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Wed, Oct 24, 2012 at 2:19 PM, Ian Kelly <ian.g.kelly at 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()
- Previous message (by thread): A lock that prioritizes acquire()s?
- Next message (by thread): A lock that prioritizes acquire()s?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list