python并发编程实战(六):线程安全问题以及Lock解决方案

线程安全概念介绍

Lock用于解决线程安全问题

未加锁导致重复扣款

现在有一个取钱的功能,如果账户余额大于取钱数量的时候,就会进行取钱操作,启动2个线程,并发的去取钱,可能会出现余额不足,但也能进行取钱的操作,如果加了等待时间,这个现象是必现的,因为sleep会造成线程的阻塞,导致线程的切换
tmp/03.lock_concurrent.py

import threading
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()

加锁

串行

为了演示串行和多线程加锁的速度,简单修改了一下代码,发现还是多线程加锁的速度更快一点

posted @ 2022-07-02 21:00  cnhkzyy  阅读(98)  评论(0编辑  收藏  举报