Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Fair Lock Recipe? #114

Closed
grantjenks opened this issue Jun 7, 2019 · 1 comment
Closed

Add Fair Lock Recipe? #114

grantjenks opened this issue Jun 7, 2019 · 1 comment

Comments

@grantjenks
Copy link
Owner

I'm not convinced of its usefulness but here's a prototype. I'm not sure how to handle two scenarios:

  1. The cache key expires and the get() returns None. Maybe we should try to add() and see if it's our turn now.
  2. 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,
        )
@grantjenks
Copy link
Owner Author

See #115

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant