--- mutex.py.orig 2004-01-29 06:37:52.000000000 +0000 +++ mutex.py 2007-07-04 06:24:32.000000000 +0000 @@ -12,13 +12,16 @@ for lock, where a function is called once the lock is aquired. """ +from __future__ import with_statement from collections import deque +from threading import Lock class mutex: def __init__(self): """Create a new mutex -- initially unlocked.""" self.locked = 0 self.queue = deque() + self.lock = Lock() def test(self): """Test the locked bit of the mutex.""" @@ -27,11 +30,12 @@ def testandset(self): """Atomic test-and-set -- grab the lock if it is not set, return True if it succeeded.""" - if not self.locked: - self.locked = 1 - return True - else: - return False + with self.lock: + if not self.locked: + self.locked = 1 + return True + else: + return False def lock(self, function, argument): """Lock a mutex, call the function with supplied argument @@ -45,8 +49,11 @@ def unlock(self): """Unlock a mutex. If the queue is not empty, call the next function with its argument.""" - if self.queue: - function, argument = self.queue.popleft() - function(argument) - else: - self.locked = 0 + call = False + with self.lock: + if self.queue: + call = True + function, argument = self.queue.popleft() + else: + self.locked = 0 + function(argument)