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. 回答1: 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