ยปCore Development>Code coverage>Lib/mutex.py

Python code coverage for Lib/mutex.py

#countcontent
1n/a"""Mutual exclusion -- for use with module sched
2n/a
3n/aA mutex has two pieces of state -- a 'locked' bit and a queue.
4n/aWhen the mutex is not locked, the queue is empty.
5n/aOtherwise, the queue contains 0 or more (function, argument) pairs
6n/arepresenting functions (or methods) waiting to acquire the lock.
7n/aWhen the mutex is unlocked while the queue is not empty,
8n/athe first queue entry is removed and its function(argument) pair called,
9n/aimplying it now has the lock.
10n/a
11n/aOf course, no multi-threading is implied -- hence the funny interface
12n/afor lock, where a function is called once the lock is aquired.
131"""
141from warnings import warnpy3k
151warnpy3k("the mutex module has been removed in Python 3.0", stacklevel=2)
161del warnpy3k
17n/a
181from collections import deque
19n/a
202class mutex:
211 def __init__(self):
22n/a """Create a new mutex -- initially unlocked."""
231 self.locked = False
241 self.queue = deque()
25n/a
261 def test(self):
27n/a """Test the locked bit of the mutex."""
283 return self.locked
29n/a
301 def testandset(self):
31n/a """Atomic test-and-set -- grab the lock if it is not set,
32n/a return True if it succeeded."""
332 if not self.locked:
341 self.locked = True
351 return True
36n/a else:
371 return False
38n/a
391 def lock(self, function, argument):
40n/a """Lock a mutex, call the function with supplied argument
41n/a when it is acquired. If the mutex is already locked, place
42n/a function and argument in the queue."""
432 if self.testandset():
441 function(argument)
45n/a else:
461 self.queue.append((function, argument))
47n/a
481 def unlock(self):
49n/a """Unlock a mutex. If the queue is not empty, call the next
50n/a function with its argument."""
512 if self.queue:
521 function, argument = self.queue.popleft()
531 function(argument)
54n/a else:
551 self.locked = False