kazoo icon indicating copy to clipboard operation
kazoo copied to clipboard

Cumbersome implementation for non-blocking Locks

Open stevemer opened this issue 11 years ago • 2 comments

Preface and disclaimer: I am a newer coder than most of y'all, so be gentle!


Opinion: This is not very clean and simple:

zk = KazooClient()
lock = zk.Lock("/lockpath", "my-identifier")
lock.acquire(blocking=False)
if lock.is_acquired:
  # do something


Opinion: This is cleaner and simpler:

zk = KazooClient()
with zk.Lock("/lockpath", "my-identifier", default_locking=False) as lock:
    if lock.is_acquired:
        # do something

And would require simply adding default_blocking=True to init_ (+ a few more lines).


Proposal:

Could we add a parameter to specify blocking behavior from init? Wouldn't change existing behavior, would (in my opinion) allow for cleaner coding, and I'd be happy to write it.


As a side rant, if pep-0377 had passed (:( ), this would be the cleanest and simplest I think?

zk = KazooClient()
with zk.Lock("/lockpath", "my-identifier", default_locking=False) as lock:
    # throw SkipException() out of __enter__ and catch into __exit__
    # do something only gets hit if we got the lock

stevemer avatar Aug 07 '14 00:08 stevemer

I don't see why we can't have a with statement version. I'll admit the main reason that I didn't include it the first time is that people get used to things being "ok" once the with block executes, and failing to check the is_acquired would be problematic.

Even with PEP-377 btw, inside a with statement, especially one that is executing for awhile, you still need/want to look at is_acquired on occasion, because the distributed lock can disappear for a variety of reasons and depending on how important it is that you don't do something when you aren't sure you have a lock....

bbangert avatar Aug 07 '14 00:08 bbangert

I've humbly written and submitted a patch - let me know if it needs improvement!

stevemer avatar Aug 07 '14 03:08 stevemer