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