sync
: Easy Mutex Creation¶
Context manager for easily using a pymemcache mutex.
The acquire_lock
context manager makes it easy to use pymemcache
(which
uses memcached) to create a mutex for a certain portion of code. Of course,
this requires the pymemcache
library to be installed, which in turn
requires memcached to be installed.
Raised when a cached lock is already in use.
-
common.sync.
acquire_lock
(lock_id, wait=0, max_retries=0)[source]¶ Acquire a lock on the given lock ID, or raise an exception.
This context manager can be used as a mutex by doing something like the following:
>>> from time import sleep >>> job_done = False >>> while not job_done: ... try: ... with acquire_lock('some id'): ... sensitive_function() ... job_done = True ... except LockUnavailable: ... # Sleep for a couple seconds while the other code runs and ... # hopefully completes ... sleep(2)
In the above example,
sensitive_function()
should only be run if no other code is also running it. A more concise way of writing the above example would be to use the other parameters, like this:>>> with acquire_lock('some id', wait=2): ... sensitive_function()
Parameters: - lock_id (str or bytes) – The ID for this lock. See
pymemcache
‘s documentation on key constraints for more info. - wait (int) – Indicates how many seconds after failing to acquire the
lock to wait (sleep) before retrying. When set to 0 (default), will
immediately raise a
LockUnavailable
exception. - max_retries (int) – Maximum number of times to retry to acquire the
lock before raising a
LockUnavailable
exception. When set to 0 (default), will always retry. Has essentially no effect ifwait
is 0.
Raises: LockUnavailable – when a lock with the same ID already exists and
wait
is set to 0.- lock_id (str or bytes) – The ID for this lock. See