数据的存储跟线程无关;一个进程中的数据在多个线程中可以直接用
list1 = [1, 2, 3]
def func1():
list1.append(100)
global list2
list2 = [4,5,6]
def func2():
list1[0] = 'hello'
print(list2) # [4, 5, 6]
t1 = Thread(target=func1())
t2 = Thread(target=func2())
t1.start()
t2.start()
print(list1) # ['hello', 2, 3, 100]
当多线程同时处理一个数据时,数据可能会产生问题;
所以引入Lock
步骤:
获取锁对象
获取数据
数操作完成后
释放锁对象
注意:使用锁的时候保证一个数据对应一把锁
"""
class Account:
def __init__(self, name, tel, balance, bank='招商银行'):
self.bank = bank
self.card_number = '392222222293093'
self.name = name
self.tel = tel
self.balance = balance
# 1.创建锁
self.lock = Lock()
def save_money(self, amount):
print('========开始存钱========')
# 2.使用锁
self.lock.acquire()
# 获取余额
bl = self.balance
print('余额:', bl)
sleep(3)
self.balance = bl + amount
# 3.释放锁
self.lock.release()
print('存钱余额:',self.balance)
print('========存钱结束========')
def draw_money(self,amount):
print('=======开始取钱!=========')
self.lock.acquire()
bl = self.balance
print('余额:',bl)
if bl < amount:
print('余额不足')
print('======取钱结束=======')
return
sleep(4)
self.balance = bl - amount
self.lock.release()
print('取钱余额:',self.balance)
print('======取钱结束======')
account = Account('hjr','232442',10000)
t1 = Thread(target=account.save_money,args=(2000,))
t2 = Thread(target=account.draw_money,args=(5000,))
t1.start()
t2.start()
t1.join()
t2.join()
print(account.balance)