《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.7 KiB

  1. #coding=utf-8
  2. #!/usr/bin/env python
  3. import threading
  4. import time
  5. condition = threading.Condition()
  6. products = 0
  7. class Producer(threading.Thread):
  8. def __init__(self):
  9. threading.Thread.__init__(self)
  10. def run(self):
  11. global condition, products
  12. while True:
  13. if condition.acquire():
  14. if products < 10:
  15. products += 1;
  16. print "Producer(%s):deliver one, now products:%s" %(self.name, products)
  17. condition.notify()
  18. else:
  19. print "Producer(%s):already 10, stop deliver, now products:%s" %(self.name, products)
  20. condition.wait();
  21. condition.release()
  22. time.sleep(2)
  23. class Consumer(threading.Thread):
  24. def __init__(self):
  25. threading.Thread.__init__(self)
  26. def run(self):
  27. global condition, products
  28. while True:
  29. if condition.acquire():
  30. if products > 1:
  31. products -= 1
  32. print "Consumer(%s):consume one, now products:%s" %(self.name, products)
  33. condition.notify()
  34. else:
  35. print "Consumer(%s):only 1, stop consume, products:%s" %(self.name, products)
  36. condition.wait();
  37. condition.release()
  38. time.sleep(2)
  39. if __name__ == "__main__":
  40. for p in range(0, 2):
  41. p = Producer()
  42. p.start()
  43. for c in range(0, 10):
  44. c = Consumer()
  45. c.start()