作为一个例子,我们会建立两个进程的死锁。假设有两把锁, x_lock 和 y_lock ,并且它们像这样使用:
x_lock = Lock() y_lock = Lock() x = 1 y = 0 def compute(): x_lock.acquire() y_lock.acquire() y = x + y x = x * x y_lock.release() x_lock.release() def anti_compute(): y_lock.acquire() x_lock.acquire() y = y - x x = sqrt(x) x_lock.release() y_lock.release()
如果 compute() 和 anti_compute() 并行执行,并且恰好像下面这样互相交错: