Python开发【笔记】:加锁的最佳方案
避开死锁
代码程序中,尽量要避免死锁的产生,下面分析常见的线程锁使用方式 ;注:只有同一把锁才会产生互斥
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开发【笔记】:加锁的最佳方案的更多相关文章
- python开发笔记-通过xml快捷获取数据
今天在做下python开发笔记之如何通过xml快捷获取数据,下面以调取nltk语料库为例: import nltk nltk.download() showing info https://raw.g ...
- python开发笔记-python调用webservice接口
环境描述: 操作系统版本: root@9deba54adab7:/# uname -a Linux 9deba54adab7 --generic #-Ubuntu SMP Thu Dec :: UTC ...
- python开发笔记-Python3.7+Django2.2 Docker镜像搭建
目标镜像环境介绍: 操作系统:ubuntu16.04 python版本:python 3.7.4 django版本:2.2 操作步骤: 1. 本地安装docker环境(略)2. 拉取ubunut指定 ...
- python开发笔记之zip()函数用法详解
今天分享一篇关于python下的zip()函数用法. zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素按顺序组合成一个tuple,每个tuple中包含的是原 ...
- Python开发笔记之正则表达式的使用
查找正则表达式 import re re_txt = re.compile(r'(\d)*.txt') m = re_txt.search(src) if not m == None: m.group ...
- python开发笔记-类
类的基本概念: 问题空间:问题空间是问题解决者对一个问题所达到的全部认识状态,它是由问题解决者利用问题所包含的信息和已贮存的信息主动的地构成的. 初始状态:一开始时的不完全的信息或令人不满意的状况: ...
- Python开发笔记之-浮点数传输
操作系统 : CentOS7.3.1611_x64 gcc版本 :4.8.5 Python 版本 : 2.7.5 思路如下 : 1.将浮点数a通过内存拷贝,赋值给相同字节的整型数据b: 2.将b转换为 ...
- Python开发笔记:网络数据抓取
网络数据获取(爬取)分为两部分: 1.抓取(抓取网页) · urlib内建模块,特别是urlib.request · Requests第三方库(中小型网络爬虫的开发) · Scrapy框架(大型网络爬 ...
- python开发笔记-ndarray方法属性详解
Python中的数组ndarray是什么? 1.NumPy中基本的数据结构 2.所有元素是同一种类型 3.别名是array 4.利于节省内存和提高CPU计算时间 5.有丰富的函数 ndarray的创建 ...
随机推荐
- iOS开发--改变tableHeaderView的高度
1.先获取tableHeaderView 2.设置它的frame 3.将该view设置回tableview UIView *view=tableView. tableHeaderView; view. ...
- redis资料
http://snowolf.iteye.com/blog/1630697 征服redis配置 http://redis.readthedocs.org/en/latest/ redis命令参考 ...
- ubuntu 上安装vnc server
Ubuntu下设置VNCServer Virtual Network Computing(VNC)是进行远程桌面控制的一个软件.客户端的键盘输入和鼠标操作通过网络传输到远程服务器,控制服务器的操作 ...
- SaltStack 批量管理任务计划
这里演示如何使用 salt-master 对多台 salt-minion 批量添加任务计划,步骤如下: [root@localhost ~]$ cat /srv/salt/top.sls # 先定义入 ...
- NUC972配置为支持NFS
系统平台:virtualbox3.2.10+ubuntu10.10 安装nfs: #sudo apt-get install nfs-kernel-server ubuntu10.10中的已经是最新版 ...
- php获取ios或android通过文件头(header)传过来的坐标,通过百度接口获取具体城市和地址,并存入到session中。
首先,在function.php方法文件中封装一个获取header头文件的方法. if (!function_exists('getallheaders')) { function getallhea ...
- 清理和关闭多余的Windows 7系统服务
清理和关闭多余的Windows 7系统服务 现在已经有不少配置不是很高的电脑用户正式用上了Windows 7(以下简称Win 7),如何让低配置电脑可以更流畅的运行Win 7呢?虽然部分软件提供了傻瓜 ...
- Qt编写可拖动对象+背景地图+多种样式+多种状态(开源)
在很多项目应用中,需要根据数据动态生成对象显示在地图上,比如地图标注,同时还需要可拖动对象到指定位置显示,能有多种状态指示,为此特意编写本控件,全部开源出来,欢迎大家提建议.同时多多支持整套自定义控件 ...
- Makefile Demo案例
# Comments can be written like this. # File should be named Makefile and then can be run as `make &l ...
- CentOS 配置Rails开发环境
1 安装mysql yum install -y mysql mysql-server 启动mysql $ /etc/init.d/mysqld start 设置root密码,删除test数据库等 / ...