【文件属性】:
文件名称:防止死锁的加锁机制-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2021-06-10 05:20:00
python cookbook 第3版 高清 中文完整版
12.5 防止死锁的加锁机制
问题
You’re writing a multithreaded program where threads need to acquire more than one lock
at a time while avoiding deadlock.
解决方案
In multithreaded programs, a common source of deadlock is due to threads that attempt to
acquire multiple locks at once. For instance, if a thread acquires the first lock, but then
blocks trying to acquire the second lock, that thread can potentially block the progress of
other threads and make the program freeze. One solution to deadlock avoidance is to
assign each lock in the program a unique number, and to enforce an ordering rule that only
allows multiple locks to be acquired in ascending order. This is surprisingly easy to
implement using a context manager as follows:
import threading from contextlib import contextmanager
# Thread-local state to stored information on locks already acquired _local =
threading.local()
@contextmanager def acquire(*locks):