mutex.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 acquired.
  11. """
  12. from warnings import warnpy3k
  13. warnpy3k("the mutex module has been removed in Python 3.0", stacklevel=2)
  14. del warnpy3k
  15. from collections import deque
  16. class mutex:
  17. def __init__(self):
  18. """Create a new mutex -- initially unlocked."""
  19. self.locked = False
  20. self.queue = deque()
  21. def test(self):
  22. """Test the locked bit of the mutex."""
  23. return self.locked
  24. def testandset(self):
  25. """Atomic test-and-set -- grab the lock if it is not set,
  26. return True if it succeeded."""
  27. if not self.locked:
  28. self.locked = True
  29. return True
  30. else:
  31. return False
  32. def lock(self, function, argument):
  33. """Lock a mutex, call the function with supplied argument
  34. when it is acquired. If the mutex is already locked, place
  35. function and argument in the queue."""
  36. if self.testandset():
  37. function(argument)
  38. else:
  39. self.queue.append((function, argument))
  40. def unlock(self):
  41. """Unlock a mutex. If the queue is not empty, call the next
  42. function with its argument."""
  43. if self.queue:
  44. function, argument = self.queue.popleft()
  45. function(argument)
  46. else:
  47. self.locked = False