mutex.py 1.8 KB

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