python怎么加锁_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

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值