I am using a Python 3 sequence like this:
lock = threading.Lock()
res = lock.acquire(timeout=10)
if res:
# do something ....
lock.release()
else:
# do something else ...
I would prefer to use a with-statement instead of explicit "acquire" and "release", but I don't know how to get the timeout effect.
A lock can be locked using the acquire() method. Once a thread has acquired the lock, all subsequent attempts to acquire the lock are blocked until it is released. The lock can be released using the release() method. Calling the release() method on a lock, in an unlocked state, results in an error.
You can use the Python Script Editor to lock a script from being viewed, edited, or deleted by certain users. To do so, select the script and then click the Lock button on the toolbar. When a script has been locked, the only users who can view or edit that script are those who have rights to edit locked items.
A mutex lock can be used to ensure that only one thread at a time executes a critical section of code at a time, while all other threads trying to execute the same code must wait until the currently executing thread is finished with the critical section and releases the lock.
You can do this pretty easily with a context manager:
import threading
from contextlib import contextmanager
@contextmanager
def acquire_timeout(lock, timeout):
result = lock.acquire(timeout=timeout)
yield result
if result:
lock.release()
# Usage:
lock = threading.Lock()
with acquire_timeout(lock, 2) as acquired:
if acquired:
print('got the lock')
# do something ....
else:
print('timeout: lock not available')
# do something else ...
*Note: This won't work in Python 2.x since there isn't a timeout
argument to Lock.acquire
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With