blob: 5d35bdf6ab0928380da79003873638ff33c426c4 [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Mutual exclusion -- for use with module sched
Guido van Rossume2e162e1991-04-21 19:32:43 +00002
Guido van Rossum54f22ed2000-02-04 15:10:34 +00003A mutex has two pieces of state -- a 'locked' bit and a queue.
4When the mutex is not locked, the queue is empty.
5Otherwise, the queue contains 0 or more (function, argument) pairs
6representing functions (or methods) waiting to acquire the lock.
7When the mutex is unlocked while the queue is not empty,
8the first queue entry is removed and its function(argument) pair called,
9implying it now has the lock.
10
11Of course, no multi-threading is implied -- hence the funny interface
12for lock, where a function is called once the lock is aquired.
13"""
14
Raymond Hettinger756b3f32004-01-29 06:37:52 +000015from collections import deque
16
Guido van Rossumce084481991-12-26 13:06:29 +000017class mutex:
Tim Peters07e99cb2001-01-14 23:47:14 +000018 def __init__(self):
19 """Create a new mutex -- initially unlocked."""
20 self.locked = 0
Raymond Hettinger756b3f32004-01-29 06:37:52 +000021 self.queue = deque()
Guido van Rossum54f22ed2000-02-04 15:10:34 +000022
Tim Peters07e99cb2001-01-14 23:47:14 +000023 def test(self):
24 """Test the locked bit of the mutex."""
25 return self.locked
Guido van Rossum54f22ed2000-02-04 15:10:34 +000026
Tim Peters07e99cb2001-01-14 23:47:14 +000027 def testandset(self):
28 """Atomic test-and-set -- grab the lock if it is not set,
Tim Petersbc0e9102002-04-04 22:55:58 +000029 return True if it succeeded."""
Tim Peters07e99cb2001-01-14 23:47:14 +000030 if not self.locked:
31 self.locked = 1
Tim Petersbc0e9102002-04-04 22:55:58 +000032 return True
Tim Peters07e99cb2001-01-14 23:47:14 +000033 else:
Tim Petersbc0e9102002-04-04 22:55:58 +000034 return False
Guido van Rossum54f22ed2000-02-04 15:10:34 +000035
Tim Peters07e99cb2001-01-14 23:47:14 +000036 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 Rossum54f22ed2000-02-04 15:10:34 +000044
Tim Peters07e99cb2001-01-14 23:47:14 +000045 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:
Raymond Hettinger756b3f32004-01-29 06:37:52 +000049 function, argument = self.queue.popleft()
Tim Peters07e99cb2001-01-14 23:47:14 +000050 function(argument)
51 else:
52 self.locked = 0