12.5 防止死锁的加锁机制

问题

You’re writing a multithreaded program where threads need to acquire more than onelock at a time while avoiding deadlock.

解决方案

In multithreaded programs, a common source of deadlock is due to threads that attemptto acquire multiple locks at once. For instance, if a thread acquires the first lock, butthen blocks trying to acquire the second lock, that thread can potentially block theprogress of other threads and make the program freeze.One solution to deadlock avoidance is to assign each lock in the program a uniquenumber, and to enforce an ordering rule that only allows multiple locks to be acquiredin ascending order. This is surprisingly easy to implement using a context manager asfollows:

import threadingfrom contextlib import contextmanager

t = threading.Thread(target=philosopher,args=(chopsticks[n],chopsticks[(n+1) % NSTICKS]))> t.start()

Last, but not least, it should be noted that in order to avoid deadlock, all locking oper‐ations must be carried out using our acquire() function. If some fragment of codedecided to acquire a lock directly, then the deadlock avoidance algorithm wouldn’t work.

文章导航