multithread6.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """
  2. 多个线程共享数据 - 有锁的情况
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-20
  6. """
  7. import time
  8. import threading
  9. class Account(object):
  10. def __init__(self):
  11. self._balance = 0
  12. self._lock = threading.Lock()
  13. def deposit(self, money):
  14. # 获得锁后代码才能继续执行
  15. self._lock.acquire()
  16. try:
  17. new_balance = self._balance + money
  18. time.sleep(0.01)
  19. self._balance = new_balance
  20. finally:
  21. # 操作完成后一定要记着释放锁
  22. self._lock.release()
  23. @property
  24. def balance(self):
  25. return self._balance
  26. if __name__ == '__main__':
  27. account = Account()
  28. # 创建100个存款的线程向同一个账户中存钱
  29. for _ in range(100):
  30. threading.Thread(target=account.deposit, args=(1,)).start()
  31. # 等所有存款的线程都执行完毕
  32. time.sleep(2)
  33. print('账户余额为: ¥%d元' % account.balance)
  34. # 想一想结果为什么不是我们期望的100元