python 模拟死锁
#
在线程间共享多个资源的时候,如果两个线程分别占有一部分资源并且同时等待对方的资源,就会造成死锁。尽管死锁很少发生,但一旦发生就会造成应用的停止响应。
如下例子:
第一个方法 lock_1 先获取 mutexA 锁,访问全局变量 globalvarA ,然后 acquire mutexB 锁
第二个方法 lock_2 先获取 mutexB 锁,访问全局变量 globakvarB ,然后 acquire mutexA 锁
当出现如下情况时发生死锁:
1. 某个线程执行到 lock_1 方法的 mutexB.acquire(1) 语句时,另一线线程执行 lock_2 方法的 mutexA.acquire(1)
由于线程是无序的,因此可能发生这种情况。
# encoding: UTF-8
import threading
import time
class MyThread(threading.Thread):
def lock_1(self):
global globalvarA, globalvarB
if mutexA.acquire():
msg = self.name+' got globalvarA'
print (msg)
if mutexB.acquire(1):
msg = self.name+' got globalvarB'
print (msg)
mutexB.release()
mutexA.release()
def lock_2(self):
global globalvarA, globalvarB
if mutexB.acquire():
msg = self.name+' got globalvarB'
print (msg)
if mutexA.acquire(1):
msg = self.name+' got globalvarA'
print (msg)
mutexA.release()
mutexB.release()
def run(self):
self.lock_1()
self.lock_2()
globalvarA = 0
globalvarB = 0
mutexA = threading.Lock()
mutexB = threading.Lock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()
执行命令
#
# 可能需要多次执行,因为线程的无序
python34 deadlock.py
结果
#
执行如上命令后,观察到已经进入死锁,光标在闪烁,无法获取下一个lock
OS上观察进程还在
[root@ ~]# ps -ef|grep -v grep|grep dead
root 19272 18226 0 11:53 pts/1 00:00:00 python34 deadlock.py
[root@ ~]#
一个线程“迭代”请求同一个资源,直接就会造成死锁
import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num = num+1
msg = self.name+' set num to '+str(num)
print (msg)
mutex.acquire()
mutex.release()
mutex.release()
num = 0
mutex = threading.Lock()
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__ == '__main__':
test()