python避免死锁方法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了python避免死锁方法。分享给大家供大家参考。具体分析如下:

当两个或者更多的线程在等待资源的时候就会产生死锁,两个线程相互等待。
在本文实例中 thread1 等待thread2释放block , thread2等待thtead1释放ablock,
 
避免死锁的原则:

1. 一定要以一个固定的顺序来取得锁,这个列子中,意味着首先要取得alock, 然后再去block

2. 一定要按照与取得锁相反的顺序释放锁,这里,应该先释放block,然后是alock

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()
  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()
t = threading.Thread(target = thread2calc)
t.setDaemon(2)
t.start()
while 1:
  time.sleep(300)

输出:

thread1 acquiring lock a
thread2 acquiring lock b
thread1 acquiring lock b
thread2 acquiring lock a

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python配置文件处理的方法教程

Python配置文件处理的方法教程

前言 在平时的工程中,我们在构建工程时,常常需要用到配置文件,用来配置项目的一些信息,比如数据库,请求网址,文件夹,线程、进程数等信息,这样就可以方便我们通过修改配置文件中的参数来很好地...

python读取二进制mnist实例详解

python读取二进制mnist实例详解 training data 数据结构: <br>[offset] [type] [value] [descrip...

Python中sort和sorted函数代码解析

本文研究的主要是Python中sort和sorted函数的相关内容,具体如下。 一、sort函数 sort函数是序列的内部函数 函数原型: L.sort(cmp=None, key=No...

Django之模板层的实现代码

在例子视图中返回文本的方式有点特别,即HTML被直接硬编码在Python代码之中。 def current_datetime(request): now = datetime.d...

python读文件保存到字典,修改字典并写入新文件的实例

实例如下所示: tcode={} transcode={} def GetTcode(): #从文本中获取英文对应的故障码,并保存在tcode字典(故障码文本样例:oxff,0xff...