Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 1 | """Mutual exclusion -- for use with module sched |
Guido van Rossum | e2e162e | 1991-04-21 19:32:43 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 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. |
| 10 | |
| 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. |
| 13 | """ |
| 14 | |
Skip Montanaro | 269b83b | 2001-02-06 01:07:02 +0000 | [diff] [blame] | 15 | __all__ = ["mutex"] |
| 16 | |
Guido van Rossum | ce08448 | 1991-12-26 13:06:29 +0000 | [diff] [blame] | 17 | class mutex: |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 18 | def __init__(self): |
| 19 | """Create a new mutex -- initially unlocked.""" |
| 20 | self.locked = 0 |
| 21 | self.queue = [] |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 22 | |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 23 | def test(self): |
| 24 | """Test the locked bit of the mutex.""" |
| 25 | return self.locked |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 26 | |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 27 | def testandset(self): |
| 28 | """Atomic test-and-set -- grab the lock if it is not set, |
| 29 | return true if it succeeded.""" |
| 30 | if not self.locked: |
| 31 | self.locked = 1 |
| 32 | return 1 |
| 33 | else: |
| 34 | return 0 |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 35 | |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 36 | def lock(self, function, argument): |
| 37 | """Lock a mutex, call the function with supplied argument |
| 38 | when it is acquired. If the mutex is already locked, place |
| 39 | function and argument in the queue.""" |
| 40 | if self.testandset(): |
| 41 | function(argument) |
| 42 | else: |
| 43 | self.queue.append((function, argument)) |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 44 | |
Tim Peters | 07e99cb | 2001-01-14 23:47:14 +0000 | [diff] [blame] | 45 | def unlock(self): |
| 46 | """Unlock a mutex. If the queue is not empty, call the next |
| 47 | function with its argument.""" |
| 48 | if self.queue: |
| 49 | function, argument = self.queue[0] |
| 50 | del self.queue[0] |
| 51 | function(argument) |
| 52 | else: |
| 53 | self.locked = 0 |