1. 线程安全问题
- 经典问题——银行取钱问题里面的核心问题
- (1)用户输入账户、密码并判断
- (2)输入取款金额
- (3)判断余额与取款金额孰多孰少
- (4)如果余额大于取款金额则取款成功;否则失败
- 若是代码如下:
import threading
import time
class Account:
def __init__(self, account_no, balance):
self.account_no = account_no
self.balance = balance
def draw(self, account, draw_amount):
if account.balance >= draw_amount:
print(threading.current_thread().name + " 取钱成功!吐出钞票:" + str(draw_amount))
time.sleep(0.0000000000000000000001)
account.balance -= draw_amount
print("余额为:" + str(account.balance))
else:
print(threading.current_thread().name + " 取钱失败,余额不足!")
if __name__ == '__main__':
acct = Account("1234567", 1000)
threading.Thread(target=acct.draw, args=(acct, 800)).start()
threading.Thread(target=acct.draw, args=(acct, 800)).start()
- 会出现如下问题:

- 所以用同步锁的方法,解决。
2. 同步锁(Lock)
import threading
import time
class Account:
def __init__(self, account_no, balance):
self.account_no = account_no
self._balance = balance
self.lock = threading.RLock()
def getBalance(self):
return self._balance
def draw(self, account, draw_amount):
self.lock.acquire()
try:
if account._balance >= draw_amount:
print(threading.current_thread().name + " 取钱成功!吐出钞票:" + str(draw_amount))
time.sleep(0.00000000000001)
account._balance -= draw_amount
print("余额为:" + str(account._balance))
else:
print(threading.current_thread().name + " 取钱失败,余额不足!")
finally:
self.lock.release()
if __name__ == '__main__':
acct = Account("1234567", 1000)
threading.Thread(target=acct.draw, args=(acct, 800)).start()
threading.Thread(target=acct.draw, args=(acct, 800)).start()
- 上面加锁之后,同一个类对象的加锁的方法只由一个线程完成,解锁之后,其它线程才可以使用。