避开死锁

代码程序中,尽量要避免死锁的产生,下面分析常见的线程锁使用方式 ;注:只有同一把锁才会产生互斥

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

  

Python开发【笔记】:加锁的最佳方案的更多相关文章

  1. python开发笔记-通过xml快捷获取数据

    今天在做下python开发笔记之如何通过xml快捷获取数据,下面以调取nltk语料库为例: import nltk nltk.download() showing info https://raw.g ...

  2. python开发笔记-python调用webservice接口

    环境描述: 操作系统版本: root@9deba54adab7:/# uname -a Linux 9deba54adab7 --generic #-Ubuntu SMP Thu Dec :: UTC ...

  3. python开发笔记-Python3.7+Django2.2 Docker镜像搭建

    目标镜像环境介绍: 操作系统:ubuntu16.04 python版本:python 3.7.4 django版本:2.2 操作步骤: 1.  本地安装docker环境(略)2. 拉取ubunut指定 ...

  4. python开发笔记之zip()函数用法详解

    今天分享一篇关于python下的zip()函数用法. zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素按顺序组合成一个tuple,每个tuple中包含的是原 ...

  5. Python开发笔记之正则表达式的使用

    查找正则表达式 import re re_txt = re.compile(r'(\d)*.txt') m = re_txt.search(src) if not m == None: m.group ...

  6. python开发笔记-类

    类的基本概念: 问题空间:问题空间是问题解决者对一个问题所达到的全部认识状态,它是由问题解决者利用问题所包含的信息和已贮存的信息主动的地构成的. 初始状态:一开始时的不完全的信息或令人不满意的状况: ...

  7. Python开发笔记之-浮点数传输

    操作系统 : CentOS7.3.1611_x64 gcc版本 :4.8.5 Python 版本 : 2.7.5 思路如下 : 1.将浮点数a通过内存拷贝,赋值给相同字节的整型数据b: 2.将b转换为 ...

  8. Python开发笔记:网络数据抓取

    网络数据获取(爬取)分为两部分: 1.抓取(抓取网页) · urlib内建模块,特别是urlib.request · Requests第三方库(中小型网络爬虫的开发) · Scrapy框架(大型网络爬 ...

  9. python开发笔记-ndarray方法属性详解

    Python中的数组ndarray是什么? 1.NumPy中基本的数据结构 2.所有元素是同一种类型 3.别名是array 4.利于节省内存和提高CPU计算时间 5.有丰富的函数 ndarray的创建 ...

随机推荐

  1. CouchDB 未授权访问漏洞

    0x00 CouchDB安装 CouchDB官方网站:http://couchdb.apache.org/ 一路Next直到完成安装,打开浏览器并访问以下链接:http://127.0.0.1:598 ...

  2. iOS开发-Autolayout小结

    昨天重点学习了下Autolayout,把以前没有吃透的概念重新理解了下,现在感觉整个人都是棒棒哒. 上一个项目是使用计算坐标代码的方式来布局UI界面,这种方式的缺点在于当苹果发布新尺寸设备时需要重写代 ...

  3. Kubernetes 相关概念

    Node: (1) Node(节点)也就是宿主机,宿主机可以是物理机 .云主机 .虚拟机等等,我们可以在一个宿主机上跑多个容器(container)(2) Node 上会被分配一些工作负载(即 doc ...

  4. Ansible 如何查看模块文档

    [root@localhost ~]$ ansible-doc -l # 列出所有模块 [root@localhost ~]$ ansible-doc cron # 查看指定模块的文档

  5. 导入贴图操作:处理贴图MaxSize和Format

    using UnityEngine; using System.Collections; using UnityEditor; public class ImportModflyTextures : ...

  6. vim 编辑基础使用-----linux编程

    Linux系统编程: VIM编辑器 | VIM Introduce 学习 vim 并且其会成为你最后一个使用的文本编辑器.没有比这个更好的文本编辑器了,非常地难学,但是却不可思议地好用. 我建议下面这 ...

  7. 在linux下搭建ftp服务器【转】

    1 安装 vsftpd yum install vsftpd 2 配置 vsftpd 打开 vsftpd 文件: vi /etc/vsftpd/vsftpd.conf 初次修改前建议备份该文件 2.1 ...

  8. 一.jquery.datatables.js表格显示

    2014年8月10日星期日 使用jquery.datatables.js取后台数据. 1.html代码 <table class="dataTables-example"&g ...

  9. springboot---->springboot中的校验器(一)

    这里面我们简单的学习一下springboot中关于数据格式化的使用.冬天花败,春暖花开,有人离去,有人归来. springboot中的校验器 我们的测试环境是springboot,对请求的person ...

  10. sencha touch 分享到微博扩展

    扩展代码: /* *分享到微博 */ Ext.define('ux.WeiboPicker', { extend: 'Ext.Picker', xtype: 'weiboPicker', config ...