线程数据安全
from time import sleep
from threading import Thread, Lock
获取锁对象
获取数据
数操作完成后
释放锁对象
注意: 使用锁的时候保证一个数据对应一把锁
class Account:
"""银行账号类"""
def __init__(self, name, tel, balance, bank='招商银行'):
self.bank = bank
self.card_number = '6233392838382383'
self.name = name
self.tel = tel
self.balance = balance
self.lock = Lock() # 1.创建锁(保证一个数据一把锁)
def save_money(self, amount):
print('=====开始存钱!======')
# 2.使用锁
self.lock.acquire()
# 获取余额
bl = self.balance
# print('存钱余额1:',bl)
sleep(2)
self.balance = bl + amount
# 3.释放锁
self.lock.release()
# print('存钱余额2:', self.balance)
print('=====存钱结束!======')
def draw_money(self, amount):
print('=====开始取钱!======')
self.lock.acquire()
bl = self.balance
# print('取钱余额1:', bl)
if bl < amount:
print('余额不足!')
print('=====取钱结束======')
return
sleep(3)
self.balance = bl - amount
self.lock.release()
# print('取钱余额2:', self.balance)
print('=====取钱结束======')
account = Account('余婷', '153000782', 10000)
t1 = Thread(target=account.save_money, args=(20000,))
t2 = Thread(target=account.draw_money, args=(5000,))
t1.start()
t2.start()
t1.join()
t2.join()
print(account.balance)
account2 = Account('小明', '23782738738', 1000)
锁的使用
from threading import *
from time import sleep
list1 = [1, 2, 3]
lock = Lock()
def func1():
lock.acquire()
global list1
list2 = list1[:]
sleep(3)
list2.append(100)
list1 = list2[:]
lock.release()
def func2():
lock.acquire()
global list1
list2 = list1[:]
sleep(3)
list2.remove(2)
list1 = list2[:]
lock.release()
t1 = Thread(target=func1)
t2 = Thread(target=func2)
t1.start()
t2.start()
t1.join()
t2.join()
print(list1)