获得Lock后,它还将在线程之间共享-Python吗?

时间:2018-07-28 07:30:31

标签: python-2.7 locking deadlock

import threading, time

a = 5
alock = threading.Lock()
b = 5
block = threading.Lock()

def thread1calc():
    print "Thread1 acquiring lock a"
    alock.acquire()
    time.sleep(5)

    print "Thread1 acquiring lock b"
    block.acquire()
    time.sleep(5)
    a += 5
    b += 5

    print "Thread1 releasing both locks"
    block.release()
    alock.release()

def thread2calc():
    print "Thread2 acquiring lock b"
    block.acquire()
    time.sleep(5)

    print "Thread2 acquiring lock a"
    alock.acquire()
    time.sleep(5)
    a += 10
    b += 10

    print "Thread2 releasing both locks"
    block.release()
    alock.release()

t = threading.Thread(target = thread1calc)
#t.setDaemon(1)
t.start()

t1 = threading.Thread(target = thread2calc)
#t1.setDaemon(2)
t1.start()

t.join()
t1.join()

print a
print b

上述程序的输出如下:

python thread_deadlock.py
Thread1 acquiring lock a
Thread2 acquiring lock b
Thread2 acquiring lock a Thread1 acquiring lock b

我试图模拟一个死锁场景,并对此行为感到困惑。在线程1获得“ a”锁之后,如果不释放线程2怎么能获得已经获得的相同锁?

0 个答案:

没有答案