避开死锁

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

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. c语言指针笔记

    一.int a[20]1. 数组名代表数组首元素的地址,不代表数组的地址2. 对数组名取地址代表整个数组的地址.a和&a代表的数据类型不一样 a代表数组首元素的地址 &a数组类型 in ...

  2. LINUX网络之ifconfig命令与ping

    ifconfig命令 网络配置 ifconfig命令被用于配置和显示Linux内核中网络接口的网络参数.用ifconfig命令配置的网卡信息,在网卡重启后机器重启后,配置就不存在.要想将上述的配置信息 ...

  3. 【转】java文件操作大全

    一.获得控制台用户输入的信息 public String getInputMessage() throws IOException...{         System.out.println(&qu ...

  4. Windows驱动中通过MDL实现用户态与核心态共享内存

    Windows驱动跑在核心态(Kernel mode),驱动的调用者跑在用户态.如何使用户态进程与核心态驱动共享内存呢 ? 我们知道32位Windows中,默认状态下虚拟空间有4G,前2G是每个进程私 ...

  5. JS - 查找同辈中的对象

    今天在使用parent().find(".a:first")的时候,发现查找结果非正常按照顺序来的.有点递归的感觉,从底层往上. 因为需要的是同级的对象,所以去查了一下jquery ...

  6. canvas - drawImage()方法绘制图片不显示的问题

    canvas有个很强大的api是drawImage()(w3c): 他的主要功能就是绘制图片.视频,甚至其他画布等.   问题: 慕名赶来,却一脚踩空,低头一看,地上一个大坑. 事情是这样的,在我看完 ...

  7. jumpserver的安装

    原文地址:http://docs.jumpserver.org/zh/docs/step_by_step.html 为了保证服务器安全,加个堡垒机,所有ssh连接都通过堡垒机来完成,堡垒机也需要有身份 ...

  8. 问题记录 为ubuntu16.04添加windows字体(解决JIRA图表乱码的问题)

    最近遇到了JIRA在新的ubuntu机器上图表的中文无法正确显示的问题,解决的方法是,为ubuntu安装中文字体,我们选择把windows上的字体复制到ubuntu上来安装的方法,步骤如下: 从win ...

  9. 【CF708E】Student's Camp 组合数+动态规划

    [CF708E]Student's Camp 题意:有一个n*m的网格,每一秒钟,所有左面没有格子的格子会有p的概率消失,右面没有格子的格子也会有p的概率消失,问你t秒钟后,整个网格的上边界和下边界仍 ...

  10. Xcode快速排错

    EXTENDS:http://blog.csdn.net/guo_hongjun1611/article/details/8063009 1,模拟器运行完全没问题,真机运行失败. 有时候我们在模拟器上 ...