Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #32067
| References | <OFB845143C.E36D6F51-ON85257AA1.0066C7C0-85257AA1.0067DD35@us.ibm.com> <CALwzidm-CnE2TmizjSTU_Cx4iCgzpX14CeTu=ZotsHBX2u2DAQ@mail.gmail.com> |
|---|---|
| From | Ian Kelly <ian.g.kelly@gmail.com> |
| Date | 2012-10-24 15:00 -0600 |
| Subject | Re: A lock that prioritizes acquire()s? |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2796.1351112441.27098.python-list@python.org> (permalink) |
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 comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: A lock that prioritizes acquire()s? Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-24 15:00 -0600
csiph-web