multithread5.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. 多个线程共享数据 - 没有锁的情况
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-20
  6. """
  7. from time import sleep
  8. from threading import Thread, Lock
  9. class Account(object):
  10. def __init__(self):
  11. self._balance = 0
  12. self._lock = Lock()
  13. def deposit(self, money):
  14. # 先获取锁才能执行后续的代码
  15. self._lock.acquire()
  16. try:
  17. new_balance = self._balance + money
  18. sleep(0.01)
  19. self._balance = new_balance
  20. finally:
  21. # 这段代码放在finally中保证释放锁的操作一定要执行
  22. self._lock.release()
  23. @property
  24. def balance(self):
  25. return self._balance
  26. class AddMoneyThread(Thread):
  27. def __init__(self, account, money):
  28. super().__init__()
  29. self._account = account
  30. self._money = money
  31. def run(self):
  32. self._account.deposit(self._money)
  33. def main():
  34. account = Account()
  35. threads = []
  36. # 创建100个存款的线程向同一个账户中存钱
  37. for _ in range(100):
  38. t = AddMoneyThread(account, 1)
  39. threads.append(t)
  40. t.start()
  41. # 等所有存款的线程都执行完毕∫
  42. for t in threads:
  43. t.join()
  44. print('账户余额为: ¥%d元' % account.balance)
  45. if __name__ == '__main__':
  46. main()