Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python lock with-statement and timeout

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.

like image 902
Tsf Avatar asked May 24 '13 17:05

Tsf


People also ask

What does lock () do in Python?

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.

How do you lock a program in Python?

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.

How do you use mutex in Python?

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.


1 Answers

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

like image 96
robbles Avatar answered Sep 22 '22 23:09

robbles