1 """Mutual exclusion -- for use with module sched
3 A mutex has two pieces of state -- a 'locked' bit and a queue.
4 When the mutex is not locked, the queue is empty.
5 Otherwise, the queue contains 0 or more (function, argument) pairs
6 representing functions (or methods) waiting to acquire the lock.
7 When the mutex is unlocked while the queue is not empty,
8 the first queue entry is removed and its function(argument) pair called,
9 implying it now has the lock.
11 Of course, no multi-threading is implied -- hence the funny interface
12 for lock, where a function is called once the lock is aquired.
17 """Create a new mutex -- initially unlocked."""
22 """Test the locked bit of the mutex."""
26 """Atomic test-and-set -- grab the lock if it is not set,
27 return True if it succeeded."""
34 def lock(self
, function
, argument
):
35 """Lock a mutex, call the function with supplied argument
36 when it is acquired. If the mutex is already locked, place
37 function and argument in the queue."""
41 self
.queue
.append((function
, argument
))
44 """Unlock a mutex. If the queue is not empty, call the next
45 function with its argument."""
47 function
, argument
= self
.queue
[0]