Closed
Description
I'm not convinced of its usefulness but here's a prototype. I'm not sure how to handle two scenarios:
- The cache key expires and the get() returns None. Maybe we should try to add() and see if it's our turn now.
- We get skipped! Depends how expiry is handled. Maybe this means getting a new ticket.
class FairLock(object):
"""Recipe for cross-process and cross-thread fair lock.
# TODO: I don't think this is correct yet. How to handle expiry?
Based on the "Ticket Lock" algorithm:
https://en.wikipedia.org/wiki/Ticket_lock
"""
def __init__(self):
self._cache.add('tickets', 0)
self._cache.add('serving', 1)
def acquire(self):
while True:
ticket = self._cache.incr(
self._tickets, expire=self._expire, tag=self._tag, retry=True,
)
while True:
serving = self._cache.get(self._serving)
if serving is None:
# Expiration occurred!
pass # TODO
elif serving < ticket:
time.sleep(0.001)
elif serving == ticket:
return
else:
assert serving > ticket
# We got skipped!
pass # TODO
def release(self):
self._cache.incr(
self._serving, expire=self._expire, tag=self._tag, retry=True,
)
Metadata
Metadata
Assignees
Labels
No labels