避开死锁

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

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. 解决ora-01034和ora-27101错误

    使用plsql登录oracle数据库,提示如下错误: 定位原因:tnsnames.ora文件中数据库的配置参数有误所致 解决办法:将SERVICE_NAME修改为SID即可

  2. Kubernetes 简介

    一.Kubernetes 相关概念 1. Kubernetes 是一个开源的容器集群管理系统,主要用来自动化部署容器 .自动扩展与收缩容器规模 .提供容器间的负载均衡2. Node:Node(节点)也 ...

  3. FTP文件下载

    using EnterpriseDT.Net.Ftp; /// <summary> /// 下载FTP文件 /// </summary> /// <param name= ...

  4. session超时跃出iframe并跳到登陆页面(转载)

    session超时跳出iframe并跳到登陆页面 在网页编程时,我们经常需要处理,当session过期时,我们要跳到登陆页面让用户登陆,由于我们可能用到IFrame框架,所以我们我登陆页面需要显示在整 ...

  5. python3 使用matplotlib画图出现中文乱码的情况

    python3使用matplotlib画图,因python3默认使用中unicode编码,所以在写代码时不再需要写 plt.xlabel(u’人数’),而是直接写plt.xlabel(‘人数’). 注 ...

  6. 《转》python学习(10)-集合

    转自 http://www.cnblogs.com/BeginMan/p/3160565.html 一.目录 1.集合概述 2.关于集合的操作符.关系符号 3.集合的一系列操作(添加.更新.访问.删除 ...

  7. 【python问题】UnicodeEncodeError: 'ascii' codec can't encode characters in position 306-309: ordinal not in range(128)

    今天在写python爬虫的时候,遇到一个问题 UnicodeEncodeError: 'ascii' codec can't encode characters in position 306-309 ...

  8. linux计划任务之crontab

    语法:        crontab [ -u user ] file        crontab [ -u user ] [ -i ] { -e | -l | -r } 说明: crontab命令 ...

  9. Sencha Touch 实战开发培训 视频教程 第二期 第三节

    2014.4.11晚上8:10分开课. 本节课耗时一小时以上. 本期培训一共八节,前两节免费,后面的课程需要付费才可以观看. 本节内容:             本地储存.扩展按钮控件.微博分享 实现 ...

  10. Struts2之命名空间与Action的三种创建方式

    看到上面的标题,相信大家已经知道我们接下来要探讨的知识了,一共两点:1.package命名空间设置:2.三种Action的创建方式.下面我们开始本篇的内容: 首先我们聊一聊命名空间的知识,namesp ...