from threading import RLock
from threading import Lock
其中RLock
是递归锁,而Lock
是互斥锁。
其区别是Rlock实例化之后该对象可以在一个线程一直去acquire()
,没有release()
,其他对象不能获取锁;Lock
是互斥锁,同一时间只能在一个线程/进程acquire()
一次,没有release()
,其他对象不能获取锁。
当同一个线程/进程需要用的2次(包含)以上的锁的时候,用Lock
就可能出现死锁的问题。这时候就需要用递归锁去解决该问题。
下面的例子是老男孩的教程中的:
from threading import RLock, Thread
import time
fork_lock = noodle_lock = RLock()
def eat1(name):
noodle_lock.acquire()
print("%s get noodles now" %name)
fork_lock.acquire()
print("%s get fork now" %name)
print("Eating noodles now")
fork_lock.release()
noodle_lock.release()
def eat2(name):
noodle_lock.acquire()
print("%s get noodles now" %name)
time.sleep(1)
fork_lock.acquire()
print("%s get fork now" %name)
print("Eating noodles now")
fork_lock.release()
noodle_lock.release()
if __name__ == "__main__":
Thread(target = eat1, args = ('test-1',)).start()
Thread(target = eat2, args = ('test-2',)).start()
Thread(target = eat1, args = ('test-3',)).start()
Thread(target = eat2, args = ('test-4',)).start()
输出:
$ py -3 subprocess_test.py
test-1 get noodles now
test-1 get fork now
Eating noodles now
test-2 get noodles now
test-2 get fork now
Eating noodles now
test-3 get noodles now
test-3 get fork now
Eating noodles now
test-4 get noodles now
test-4 get fork now
Eating noodles now
网友评论