example21.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. 多个线程竞争一个资源 - 保护临界资源 - 锁(Lock/RLock)
  3. 多个线程竞争多个资源(线程数>资源数) - 信号量(Semaphore)
  4. 多个线程的调度 - 暂停线程执行/唤醒等待中的线程 - Condition
  5. """
  6. from concurrent.futures import ThreadPoolExecutor
  7. from random import randint
  8. from time import sleep
  9. import threading
  10. class Account():
  11. """银行账户"""
  12. def __init__(self, balance=0):
  13. self.balance = balance
  14. lock = threading.Lock()
  15. self.condition = threading.Condition(lock)
  16. def withdraw(self, money):
  17. """取钱"""
  18. with self.condition:
  19. while money > self.balance:
  20. self.condition.wait()
  21. new_balance = self.balance - money
  22. sleep(0.001)
  23. self.balance = new_balance
  24. def deposit(self, money):
  25. """存钱"""
  26. with self.condition:
  27. new_balance = self.balance + money
  28. sleep(0.001)
  29. self.balance = new_balance
  30. self.condition.notify_all()
  31. def add_money(account):
  32. while True:
  33. money = randint(5, 10)
  34. account.deposit(money)
  35. print(threading.current_thread().name,
  36. ':', money, '====>', account.balance)
  37. sleep(0.5)
  38. def sub_money(account):
  39. while True:
  40. money = randint(10, 30)
  41. account.withdraw(money)
  42. print(threading.current_thread().name,
  43. ':', money, '<====', account.balance)
  44. sleep(1)
  45. def main():
  46. account = Account()
  47. with ThreadPoolExecutor(max_workers=10) as pool:
  48. for _ in range(5):
  49. pool.submit(add_money, account)
  50. pool.submit(sub_money, account)
  51. if __name__ == '__main__':
  52. main()