Is there a way to implement a lock in Python for multithreading purposes whose acquire method can have an arbitrary timeout? The only working solutions I found so far use polling, which
- I find inelegant and inefficient
- Doesn’t preserve the bounded waiting / progress guarantee of the lock as a solution to the critical section problem
Is there a better way to implement this?
to elaborate on Steven’s comment suggestion:
Things to notice:
threading.Lock()objects, one is internal to thethreading.Condition().cond, it’s lock is acquired; thewait()operation unlocks it, though, so any number of threads can watch it.threading.Conditioncan become notified for reasons other than timeouts, so you still need to track the time if you really want it to expire.waitLockfunction should follow alock.release()with acond.notify()so that other threads waiting on it are notified that they should retry aquiring the lock. This is not shown in the example.