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的创建 ...
随机推荐
- CPU特性漏洞测试(Meltdown and Spectre)
2018年1月4日,国外安全研究人员披露了名为"Meltdown"和"Spectre"两组CPU特性漏洞,该漏洞波及到近20年的Intel, AMD, Qual ...
- 【转载】浅谈TDD、BDD与ATDD软件开发
转载自(此处仅供学习):http://blog.csdn.net/zhenyu5211314/article/details/22033295 1. 首先了解一下这三个开发模式都是什么意思: TDD: ...
- Memcached 命令行操作
telnet 用于连接 Memcached: [root@localhost ~]# telnet Trying 127.0.0.1... Connected to 127.0.0.1. Escape ...
- GNU Readline库函数的应用示例
说明 GNU Readline是一个跨平台开源程序库,提供交互式的文本编辑功能.应用程序借助该库函数,允许用户编辑键入的命令行,并提供自动补全和命令历史等功能.Bash(Bourne Again Sh ...
- 【Python3】 django2.0 url 跳转设置
python: 3.6.4 django : 2.0 在创建应用时候.我是把 urls.py 分开了.所以在设置url跳转时候.要修改成如下模式 1 父 urls.py 里边要加上命名空间 2 ...
- Windows server 创建FTP 包括ftp的账号密码设置
原始文章 : https://blog.csdn.net/missingshirely/article/details/50767043 最近要做个FTP上传资源的工具,以前都是我提供目录,由公司网管 ...
- java基础---->git的使用(一)
这里面记录一下git的使用,只是平时工作中遇到的一些问题的解决方案,不会涉及到git的一些基础概念及说明.人的天性便是这般凉薄,只要拿更好的来换,一定舍得. Git的一些使用 一.在码云建立好仓库之后 ...
- QT开发之旅四邮件发送工具
终于有了一个晚上安静的写写程序,最近一直忙着公司商务上的事情,一直想用QT实现一个调用最底层socket通信来实现的邮件发送程序,以前用C#写过,微软都封装好的,不知道底层是如何实现的,只知道调用方法 ...
- 【大数据系列】安装Ambari
一.Ambari简介 The Apache Ambari project is aimed at making Hadoop management simpler by developing soft ...
- intellij2016.03激活
激活的时候采用server的方式 :http://jetbrains.tech