線程數(shù)據(jù)安全
from time import sleep
from threading import Thread, Lock
獲取鎖對(duì)象
獲取數(shù)據(jù)
數(shù)操作完成后
釋放鎖對(duì)象
注意: 使用鎖的時(shí)候保證一個(gè)數(shù)據(jù)對(duì)應(yīng)一把鎖
class Account:
"""銀行賬號(hào)類"""
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.創(chuàng)建鎖(保證一個(gè)數(shù)據(jù)一把鎖)
def save_money(self, amount):
print('=====開(kāi)始存錢递沪!======')
# 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('=====存錢結(jié)束!======')
def draw_money(self, amount):
print('=====開(kāi)始取錢僚焦!======')
self.lock.acquire()
bl = self.balance
# print('取錢余額1:', bl)
if bl < amount:
print('余額不足!')
print('=====取錢結(jié)束======')
return
sleep(3)
self.balance = bl - amount
self.lock.release()
# print('取錢余額2:', self.balance)
print('=====取錢結(jié)束======')
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)