Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #32067 > unrolled thread
| Started by | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| First post | 2012-10-24 15:00 -0600 |
| Last post | 2012-10-24 15:00 -0600 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: A lock that prioritizes acquire()s? Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-24 15:00 -0600
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2012-10-24 15:00 -0600 |
| Subject | Re: A lock that prioritizes acquire()s? |
| Message-ID | <mailman.2796.1351112441.27098.python-list@python.org> |
On Wed, Oct 24, 2012 at 2:19 PM, Ian Kelly <ian.g.kelly@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()
Back to top | Article view | comp.lang.python
csiph-web