我有以下一段代码。
import multiprocessing as mp
import time
def f(l,a):
print("Acquiring lock in f")
l.acquire()
time.sleep(2)
try:
a.put([2,3])
a.get()
print("In f a is: ", a.get())
finally:
l.release()
print("Just released lock in f")
def g(l,a):
print("Acquiring lock in g")
time.sleep(1)
print(l.acquire())
try:
print("In g a is: ",a.get())
finally:
print("In finally")
l.release()
if __name__ == '__main__':
l = mp.RLock()
data = mp.Queue()
data.put([1])
p1 = mp.Process(target=f, args=(l,data))
p2 = mp.Process(target=g, args=(l,data))
p1.start()
p2.start()
p2.join()
p1.join()
l.acquire()
输出显示g()中的Lock.acquire()不允许进一步执行,即使在其他地方释放该锁时它返回True。知道这里有什么问题吗?我使用了Lock而不是RLock,没有打印出yield()返回值的结果,没有使用try和finally块,但是总会得到相同的结果。
$ python first.py
Acquiring lock in f
Acquiring lock in g
In f a is: [2, 3]
Just released lock in finally
True