mutex.py 1.82 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
"""Mutual exclusion -- for use with module sched

A mutex has two pieces of state -- a 'locked' bit and a queue.
When the mutex is not locked, the queue is empty.
Otherwise, the queue contains 0 or more (function, argument) pairs
representing functions (or methods) waiting to acquire the lock.
When the mutex is unlocked while the queue is not empty,
the first queue entry is removed and its function(argument) pair called,
implying it now has the lock.

Of course, no multi-threading is implied -- hence the funny interface
for lock, where a function is called once the lock is aquired.
"""
14 15 16
from warnings import warnpy3k
warnpy3k("the mutex module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
Guido van Rossum's avatar
Guido van Rossum committed
17

18 19
from collections import deque

Guido van Rossum's avatar
Guido van Rossum committed
20
class mutex:
Tim Peters's avatar
Tim Peters committed
21 22 23
    def __init__(self):
        """Create a new mutex -- initially unlocked."""
        self.locked = 0
24
        self.queue = deque()
25

Tim Peters's avatar
Tim Peters committed
26 27 28
    def test(self):
        """Test the locked bit of the mutex."""
        return self.locked
29

Tim Peters's avatar
Tim Peters committed
30 31
    def testandset(self):
        """Atomic test-and-set -- grab the lock if it is not set,
32
        return True if it succeeded."""
Tim Peters's avatar
Tim Peters committed
33 34
        if not self.locked:
            self.locked = 1
35
            return True
Tim Peters's avatar
Tim Peters committed
36
        else:
37
            return False
38

Tim Peters's avatar
Tim Peters committed
39 40 41 42 43 44 45 46
    def lock(self, function, argument):
        """Lock a mutex, call the function with supplied argument
        when it is acquired.  If the mutex is already locked, place
        function and argument in the queue."""
        if self.testandset():
            function(argument)
        else:
            self.queue.append((function, argument))
47

Tim Peters's avatar
Tim Peters committed
48 49 50 51
    def unlock(self):
        """Unlock a mutex.  If the queue is not empty, call the next
        function with its argument."""
        if self.queue:
52
            function, argument = self.queue.popleft()
Tim Peters's avatar
Tim Peters committed
53 54 55
            function(argument)
        else:
            self.locked = 0