《操作系统》的实验代码。
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.

42 rivejä
1.1 KiB

  1. import threading
  2. counterA = 0
  3. counterB = 0
  4. mutexA = threading.Lock()
  5. mutexB = threading.Lock()
  6. class MyThread(threading.Thread):
  7. def __init__(self):
  8. threading.Thread.__init__(self)
  9. def run(self):
  10. self.fun1()
  11. self.fun2()
  12. def fun1(self):
  13. global mutexA, mutexB
  14. if mutexA.acquire():
  15. print "I am %s , get res: %s" %(self.name, "ResA")
  16. if mutexB.acquire():
  17. print "I am %s , get res: %s" %(self.name, "ResB")
  18. mutexB.release()
  19. mutexA.release()
  20. def fun2(self):
  21. global mutexA, mutexB
  22. if mutexB.acquire():
  23. print "I am %s , get res: %s" %(self.name, "ResB")
  24. if mutexA.acquire():
  25. print "I am %s , get res: %s" %(self.name, "ResA")
  26. mutexA.release()
  27. mutexB.release()
  28. if __name__ == "__main__":
  29. for i in range(0, 100):
  30. my_thread = MyThread()
  31. my_thread.start()