blob: 3e21dfec853a190d7e68d6002505382f82e61d9c [file] [log] [blame]
Benjamin Peterson7f03ea72008-06-13 19:20:48 +00001#
2# Module implementing synchronization primitives
3#
4# multiprocessing/synchronize.py
5#
6# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
7#
8
9__all__ = [
10 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event'
11 ]
12
13import threading
14import os
15import sys
16
17from time import time as _time, sleep as _sleep
18
19import _multiprocessing
20from multiprocessing.process import current_process
21from multiprocessing.util import Finalize, register_after_fork, debug
22from multiprocessing.forking import assert_spawning, Popen
23
24#
25# Constants
26#
27
28RECURSIVE_MUTEX, SEMAPHORE = range(2)
29SEM_VALUE_MAX = _multiprocessing.SemLock.SEM_VALUE_MAX
30
31#
32# Base class for semaphores and mutexes; wraps `_multiprocessing.SemLock`
33#
34
35class SemLock(object):
36
37 def __init__(self, kind, value, maxvalue):
38 sl = self._semlock = _multiprocessing.SemLock(kind, value, maxvalue)
39 debug('created semlock with handle %s' % sl.handle)
40 self._make_methods()
41
42 if sys.platform != 'win32':
43 def _after_fork(obj):
44 obj._semlock._after_fork()
45 register_after_fork(self, _after_fork)
46
47 def _make_methods(self):
48 self.acquire = self._semlock.acquire
49 self.release = self._semlock.release
50 self.__enter__ = self._semlock.__enter__
51 self.__exit__ = self._semlock.__exit__
52
53 def __getstate__(self):
54 assert_spawning(self)
55 sl = self._semlock
56 return (Popen.duplicate_for_child(sl.handle), sl.kind, sl.maxvalue)
57
58 def __setstate__(self, state):
59 self._semlock = _multiprocessing.SemLock._rebuild(*state)
60 debug('recreated blocker with handle %r' % state[0])
61 self._make_methods()
62
63#
64# Semaphore
65#
66
67class Semaphore(SemLock):
Jesse Noller27cc8e12008-09-01 16:47:25 +000068 '''
69 A semaphore object
70 '''
Benjamin Peterson7f03ea72008-06-13 19:20:48 +000071 def __init__(self, value=1):
72 SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX)
73
74 def get_value(self):
75 return self._semlock._get_value()
76
77 def __repr__(self):
78 try:
79 value = self._semlock._get_value()
80 except Exception:
81 value = 'unknown'
82 return '<Semaphore(value=%s)>' % value
83
84#
85# Bounded semaphore
86#
87
88class BoundedSemaphore(Semaphore):
Jesse Noller27cc8e12008-09-01 16:47:25 +000089 '''
90 A bounded semaphore object
91 '''
Benjamin Peterson7f03ea72008-06-13 19:20:48 +000092 def __init__(self, value=1):
93 SemLock.__init__(self, SEMAPHORE, value, value)
94
95 def __repr__(self):
96 try:
97 value = self._semlock._get_value()
98 except Exception:
99 value = 'unknown'
100 return '<BoundedSemaphore(value=%s, maxvalue=%s)>' % \
101 (value, self._semlock.maxvalue)
102
103#
104# Non-recursive lock
105#
106
107class Lock(SemLock):
Jesse Noller27cc8e12008-09-01 16:47:25 +0000108 '''
109 A non-recursive lock object
110 '''
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000111 def __init__(self):
112 SemLock.__init__(self, SEMAPHORE, 1, 1)
113
114 def __repr__(self):
115 try:
116 if self._semlock._is_mine():
Jesse Noller5bc9f4c2008-08-19 19:06:19 +0000117 name = current_process().name
118 if threading.current_thread().name != 'MainThread':
119 name += '|' + threading.current_thread().name
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000120 elif self._semlock._get_value() == 1:
121 name = 'None'
122 elif self._semlock._count() > 0:
123 name = 'SomeOtherThread'
124 else:
125 name = 'SomeOtherProcess'
126 except Exception:
127 name = 'unknown'
128 return '<Lock(owner=%s)>' % name
129
130#
131# Recursive lock
132#
133
134class RLock(SemLock):
Jesse Noller27cc8e12008-09-01 16:47:25 +0000135 '''
136 A recursive lock object
137 '''
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000138 def __init__(self):
139 SemLock.__init__(self, RECURSIVE_MUTEX, 1, 1)
140
141 def __repr__(self):
142 try:
143 if self._semlock._is_mine():
Jesse Noller5bc9f4c2008-08-19 19:06:19 +0000144 name = current_process().name
145 if threading.current_thread().name != 'MainThread':
146 name += '|' + threading.current_thread().name
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000147 count = self._semlock._count()
148 elif self._semlock._get_value() == 1:
149 name, count = 'None', 0
150 elif self._semlock._count() > 0:
151 name, count = 'SomeOtherThread', 'nonzero'
152 else:
153 name, count = 'SomeOtherProcess', 'nonzero'
154 except Exception:
155 name, count = 'unknown', 'unknown'
156 return '<RLock(%s, %s)>' % (name, count)
157
158#
159# Condition variable
160#
161
162class Condition(object):
Jesse Noller27cc8e12008-09-01 16:47:25 +0000163 '''
164 A condition object
165 '''
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000166
167 def __init__(self, lock=None):
168 self._lock = lock or RLock()
169 self._sleeping_count = Semaphore(0)
170 self._woken_count = Semaphore(0)
171 self._wait_semaphore = Semaphore(0)
172 self._make_methods()
173
174 def __getstate__(self):
175 assert_spawning(self)
176 return (self._lock, self._sleeping_count,
177 self._woken_count, self._wait_semaphore)
178
179 def __setstate__(self, state):
180 (self._lock, self._sleeping_count,
181 self._woken_count, self._wait_semaphore) = state
182 self._make_methods()
183
184 def _make_methods(self):
185 self.acquire = self._lock.acquire
186 self.release = self._lock.release
187 self.__enter__ = self._lock.__enter__
188 self.__exit__ = self._lock.__exit__
189
190 def __repr__(self):
191 try:
192 num_waiters = (self._sleeping_count._semlock._get_value() -
193 self._woken_count._semlock._get_value())
194 except Exception:
195 num_waiters = 'unkown'
196 return '<Condition(%s, %s)>' % (self._lock, num_waiters)
197
198 def wait(self, timeout=None):
199 assert self._lock._semlock._is_mine(), \
200 'must acquire() condition before using wait()'
201
202 # indicate that this thread is going to sleep
203 self._sleeping_count.release()
204
205 # release lock
206 count = self._lock._semlock._count()
207 for i in xrange(count):
208 self._lock.release()
209
210 try:
211 # wait for notification or timeout
212 self._wait_semaphore.acquire(True, timeout)
213 finally:
214 # indicate that this thread has woken
215 self._woken_count.release()
216
217 # reacquire lock
218 for i in xrange(count):
219 self._lock.acquire()
220
221 def notify(self):
222 assert self._lock._semlock._is_mine(), 'lock is not owned'
223 assert not self._wait_semaphore.acquire(False)
224
225 # to take account of timeouts since last notify() we subtract
226 # woken_count from sleeping_count and rezero woken_count
227 while self._woken_count.acquire(False):
228 res = self._sleeping_count.acquire(False)
229 assert res
230
231 if self._sleeping_count.acquire(False): # try grabbing a sleeper
232 self._wait_semaphore.release() # wake up one sleeper
233 self._woken_count.acquire() # wait for the sleeper to wake
234
235 # rezero _wait_semaphore in case a timeout just happened
236 self._wait_semaphore.acquire(False)
237
238 def notify_all(self):
239 assert self._lock._semlock._is_mine(), 'lock is not owned'
240 assert not self._wait_semaphore.acquire(False)
241
242 # to take account of timeouts since last notify*() we subtract
243 # woken_count from sleeping_count and rezero woken_count
244 while self._woken_count.acquire(False):
245 res = self._sleeping_count.acquire(False)
246 assert res
247
248 sleepers = 0
249 while self._sleeping_count.acquire(False):
250 self._wait_semaphore.release() # wake up one sleeper
251 sleepers += 1
252
253 if sleepers:
254 for i in xrange(sleepers):
255 self._woken_count.acquire() # wait for a sleeper to wake
256
257 # rezero wait_semaphore in case some timeouts just happened
258 while self._wait_semaphore.acquire(False):
259 pass
260
261#
262# Event
263#
264
265class Event(object):
Jesse Noller27cc8e12008-09-01 16:47:25 +0000266 '''
267 An event object
268 '''
Benjamin Peterson7f03ea72008-06-13 19:20:48 +0000269 def __init__(self):
270 self._cond = Condition(Lock())
271 self._flag = Semaphore(0)
272
273 def is_set(self):
274 self._cond.acquire()
275 try:
276 if self._flag.acquire(False):
277 self._flag.release()
278 return True
279 return False
280 finally:
281 self._cond.release()
282
283 def set(self):
284 self._cond.acquire()
285 try:
286 self._flag.acquire(False)
287 self._flag.release()
288 self._cond.notify_all()
289 finally:
290 self._cond.release()
291
292 def clear(self):
293 self._cond.acquire()
294 try:
295 self._flag.acquire(False)
296 finally:
297 self._cond.release()
298
299 def wait(self, timeout=None):
300 self._cond.acquire()
301 try:
302 if self._flag.acquire(False):
303 self._flag.release()
304 else:
305 self._cond.wait(timeout)
306 finally:
307 self._cond.release()