Python多线程:线程安全与lock锁的应用

什么叫线程安全?
线程安全是指某个函数、函数库在多线程环境中被调用时,能够正确的处理多个线程之间的共享变量,使程序功能能够正确的完成。
lock 锁能做什么?
当然是解决线程安全问题了。!!!!

本篇所用的的类库

import threading
import time

我们的代码分两段,一段是会出现问题的,一段是不会出现问题的

import threading
import time

lock = threading.Lock()


class Account:
    def __init__(self, balance):
        self.balance = balance

def draw(account, amount):
    if account.balance >= amount:
        time.sleep(0.1)   # 去除lock,加上停止指定报错
        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()

下面的代码不会出问题,兄弟,找不同吧

import threading
import time

lock = threading.Lock()


class Account:
    def __init__(self, balance):
        self.balance = balance

def draw(account, amount):
    with lock:
        if account.balance >= amount:
            time.sleep(0.1)   # 去除lock,加上停止指定报错
            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()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宿夏星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值