您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Mutual exclusion -- for use with module sched
  2. A mutex has two pieces of state -- a 'locked' bit and a queue.
  3. When the mutex is not locked, the queue is empty.
  4. Otherwise, the queue contains 0 or more (function, argument) pairs
  5. representing functions (or methods) waiting to acquire the lock.
  6. When the mutex is unlocked while the queue is not empty,
  7. the first queue entry is removed and its function(argument) pair called,
  8. implying it now has the lock.
  9. Of course, no multi-threading is implied -- hence the funny interface
  10. for lock, where a function is called once the lock is aquired.
  11. """
  12. class mutex:
  13. def __init__(self):
  14. """Create a new mutex -- initially unlocked."""
  15. self.locked = 0
  16. self.queue = []
  17. def test(self):
  18. """Test the locked bit of the mutex."""
  19. return self.locked
  20. def testandset(self):
  21. """Atomic test-and-set -- grab the lock if it is not set,
  22. return true if it succeeded."""
  23. if not self.locked:
  24. self.locked = 1
  25. return 1
  26. else:
  27. return 0
  28. def lock(self, function, argument):
  29. """Lock a mutex, call the function with supplied argument
  30. when it is acquired. If the mutex is already locked, place
  31. function and argument in the queue."""
  32. if self.testandset():
  33. function(argument)
  34. else:
  35. self.queue.append((function, argument))
  36. def unlock(self):
  37. """Unlock a mutex. If the queue is not empty, call the next
  38. function with its argument."""
  39. if self.queue:
  40. function, argument = self.queue[0]
  41. del self.queue[0]
  42. function(argument)
  43. else:
  44. self.locked = 0