do_lock.py 687 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import time, threading
  4. # 假定这是你的银行存款:
  5. balance = 0
  6. lock = threading.Lock()
  7. def change_it(n):
  8. # 先存后取,结果应该为0:
  9. global balance
  10. balance = balance + n
  11. balance = balance - n
  12. def run_thread(n):
  13. for i in range(100000):
  14. # 先要获取锁:
  15. lock.acquire()
  16. try:
  17. # 放心地改吧:
  18. change_it(n)
  19. finally:
  20. # 改完了一定要释放锁:
  21. lock.release()
  22. t1 = threading.Thread(target=run_thread, args=(5,))
  23. t2 = threading.Thread(target=run_thread, args=(8,))
  24. t1.start()
  25. t2.start()
  26. t1.join()
  27. t2.join()
  28. print(balance)