Python开发【笔记】:加锁的最佳方案
2018-06-18 02:57:31来源:未知 阅读 ()
避开死锁
代码程序中,尽量要避免死锁的产生,下面分析常见的线程锁使用方式 ;注:只有同一把锁才会产生互斥
1、常见的死锁方式(加锁时程序报错,锁未释放):
import time import threading class Lock(): def __init__(self): self.mutex = threading.Lock() def error(self): try: self.mutex.acquire() a = '1' b = 2 print(a+b) self.mutex.release() except Exception as e: print(e) def safe(self): try: self.mutex.acquire() a = 1 b = 2 print(a + b) self.mutex.release() except Exception as e: print(e) def func1(cls): while True: cls.safe() time.sleep(0.1) def func2(cls): while True: cls.error() time.sleep(0.1) if __name__ == '__main__': lock = Lock() t1 = threading.Thread(target=func1,args=(lock,)) t1.start() t2 = threading.Thread(target=func2,args=(lock,)) t2.start() # 3 # must be str, not int
执行上面代码,异常抛出时,锁未释放,程序卡死
2、修补代码死锁情况(抛异常处添加锁释放):
import time import threading class Lock(): def __init__(self): self.mutex = threading.Lock() def error(self): try: self.mutex.acquire() a = '1' b = 2 print(a+b) self.mutex.release() except Exception as e: print(e) self.mutex.release() def safe(self): try: self.mutex.acquire() a = 1 b = 2 print(a + b) self.mutex.release() except Exception as e: print(e) def func1(cls): while True: cls.safe() time.sleep(0.1) def func2(cls): while True: cls.error() time.sleep(0.1) if __name__ == '__main__': lock = Lock() t1 = threading.Thread(target=func1,args=(lock,)) t1.start() t2 = threading.Thread(target=func2,args=(lock,)) t2.start() # 3 # must be str, not int # must be str, not int # 3 # 3
3、最佳方案(不用手动释放,即使异常也会自动释放):
import time import threading class Lock(): def __init__(self): self.mutex = threading.Lock() def error(self): try: with self.mutex: a = '1' b = 2 print(a+b) except Exception as e: print(e) def safe(self): try: with self.mutex: a = 1 b = 2 print(a + b) except Exception as e: print(e) def func1(cls): while True: cls.safe() time.sleep(0.1) def func2(cls): while True: cls.error() time.sleep(0.1) if __name__ == '__main__': lock = Lock() t1 = threading.Thread(target=func1,args=(lock,)) t1.start() t2 = threading.Thread(target=func2,args=(lock,)) t2.start() # 3 # must be str, not int # 3 # must be str, not int # 3 # must be str, not int
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:类
- python3基础之“术语表(2)” 2019-08-13
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等 2019-08-13
- Python3安装impala 2019-08-13
- 小白如何入门 Python 爬虫? 2019-08-13
- python_字符串方法 2019-08-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash