Python并发编程实战(六):如何应对线程安全及Lock机制应用?
- 内容介绍
- 文章标签
- 相关推荐
本文共计383个文字,预计阅读时间需要2分钟。
程序安全概念介绍 + Lock用于解决线程安全问题 + 未加锁导致重复扣款 + 现在有取款功能,若账户余额大于取款数量,则进行取款操作,启动2个线程,并发地去取款,可能
线程安全概念介绍
Lock用于解决线程安全问题
未加锁导致重复扣款
现在有一个取钱的功能,如果账户余额大于取钱数量的时候,就会进行取钱操作,启动2个线程,并发的去取钱,可能会出现余额不足,但也能进行取钱的操作,如果加了等待时间,这个现象是必现的,因为sleep会造成线程的阻塞,导致线程的切换
tmp/03.lock_concurrent.py
import time
class Account:
def __init__(self, balance):
self.balance = balance
def draw(account, amount):
if account.balance >= amount:
#sleep会导致线程的阻塞,导致线程的切换,因此加了sleep每次都会出现
time.sleep(0.1)
print(threading.current_thread().name, "取钱成功")
account.balance -= amount
print(threading.current_thread().name, "余额", account.balance)
else:
print(threading.current_thread().name, "取钱失败,余额不足")
if __name__ == '__main__':
account = Account(1000)
ta = threading.Thread(name="ta", target=draw, args=(account, 800))
tb = threading.Thread(name="tb", target=draw, args=(account, 800))
ta.start()
tb.start()
加锁
串行
为了演示串行和多线程加锁的速度,简单修改了一下代码,发现还是多线程加锁的速度更快一点
本文共计383个文字,预计阅读时间需要2分钟。
程序安全概念介绍 + Lock用于解决线程安全问题 + 未加锁导致重复扣款 + 现在有取款功能,若账户余额大于取款数量,则进行取款操作,启动2个线程,并发地去取款,可能
线程安全概念介绍
Lock用于解决线程安全问题
未加锁导致重复扣款
现在有一个取钱的功能,如果账户余额大于取钱数量的时候,就会进行取钱操作,启动2个线程,并发的去取钱,可能会出现余额不足,但也能进行取钱的操作,如果加了等待时间,这个现象是必现的,因为sleep会造成线程的阻塞,导致线程的切换
tmp/03.lock_concurrent.py
import time
class Account:
def __init__(self, balance):
self.balance = balance
def draw(account, amount):
if account.balance >= amount:
#sleep会导致线程的阻塞,导致线程的切换,因此加了sleep每次都会出现
time.sleep(0.1)
print(threading.current_thread().name, "取钱成功")
account.balance -= amount
print(threading.current_thread().name, "余额", account.balance)
else:
print(threading.current_thread().name, "取钱失败,余额不足")
if __name__ == '__main__':
account = Account(1000)
ta = threading.Thread(name="ta", target=draw, args=(account, 800))
tb = threading.Thread(name="tb", target=draw, args=(account, 800))
ta.start()
tb.start()
加锁
串行
为了演示串行和多线程加锁的速度,简单修改了一下代码,发现还是多线程加锁的速度更快一点

