Debian Codegraph @

pypy/module/thread/os_lock.py

raw symbols SCIP
1 """
2 Python locks, based on true threading locks provided by the OS.
3 """
4
5 import time
6 from rpython.rlib import rthread
7 from pypy.module.thread.error import wrap_thread_error
8 from pypy.interpreter.baseobjspace import W_Root
9 from pypy.interpreter.gateway import interp2app, unwrap_spec
10 from pypy.interpreter.typedef import TypeDef, make_weakref_descr
11 from pypy.interpreter.error import oefmt
12 from rpython.rlib.rarithmetic import r_longlong, ovfcheck, ovfcheck_float_to_longlong
13
14 # Force the declaration of the type 'thread.LockType' for RPython
15 #import pypy.module.thread.rpython.exttable
16
17 LONGLONG_MAX = r_longlong(2 ** (r_longlong.BITS - 1) - 1)
18 TIMEOUT_MAX = LONGLONG_MAX
19
20 RPY_LOCK_FAILURE, RPY_LOCK_ACQUIRED, RPY_LOCK_INTR = range(3)
21
22
23 def parse_acquire_args(space, blocking, timeout):
24 if not blocking and timeout != -1.0:
25 raise oefmt(space.w_ValueError,
26 "can't specify a timeout for a non-blocking call")
27 if timeout < 0.0 and timeout != -1.0:
28 raise oefmt(space.w_ValueError,
29 "timeout value must be strictly positive")
30 if not blocking:
31 microseconds = 0
32 elif timeout == -1.0:
33 microseconds = -1
34 else:
35 timeout *= 1e6
36 try:
37 microseconds = ovfcheck_float_to_longlong(timeout)
38 except OverflowError:
39 raise oefmt(space.w_OverflowError, "timeout value is too large")
40 return microseconds
41
42
43 def acquire_timed(space, lock, microseconds):
44 """Helper to acquire an interruptible lock with a timeout."""
45 endtime = (time.time() * 1e6) + microseconds
46 while True:
47 result = lock.acquire_timed(microseconds)
48 if result == RPY_LOCK_INTR:
49 # Run signal handlers if we were interrupted
50 space.getexecutioncontext().checksignals()
51 if microseconds >= 0:
52 microseconds = r_longlong((endtime - (time.time() * 1e6))
53 + 0.999)
54 # Check for negative values, since those mean block
55 # forever
56 if microseconds <= 0:
57 result = RPY_LOCK_FAILURE
58 if result != RPY_LOCK_INTR:
59 break
60 return result
61
62
63 class Lock(W_Root):
64 "A wrappable box around an interp-level lock object."
65
66 _immutable_fields_ = ["lock"]
67
68 def __init__(self, space):
69 self.space = space
70 try:
71 self.lock = rthread.allocate_lock()
72 except rthread.error:
73 raise wrap_thread_error(space, "out of resources")
74
75 @unwrap_spec(blocking=int, timeout=float)
76 def descr_lock_acquire(self, space, blocking=1, timeout=-1.0):
77 """Lock the lock. Without argument, this blocks if the lock is already
78 locked (even by the same thread), waiting for another thread to release
79 the lock, and return None once the lock is acquired.
80 With an argument, this will only block if the argument is true,
81 and the return value reflects whether the lock is acquired.
82 The blocking operation is interruptible."""
83 microseconds = parse_acquire_args(space, blocking, timeout)
84 result = acquire_timed(space, self.lock, microseconds)
85 return space.newbool(result == RPY_LOCK_ACQUIRED)
86
87 def descr_lock_release(self, space):
88 """Release the lock, allowing another thread that is blocked waiting for
89 the lock to acquire the lock. The lock must be in the locked state,
90 but it needn't be locked by the same thread that unlocks it."""
91 try:
92 self.lock.release()
93 except rthread.error:
94 raise oefmt(space.w_RuntimeError,
95 "cannot release un-acquired lock")
96
97 def _is_locked(self):
98 if self.lock.acquire(False):
99 self.lock.release()
100 return False
101 else:
102 return True
103
104 def descr_lock_locked(self, space):
105 """Return whether the lock is in the locked state."""
106 return space.newbool(self._is_locked())
107
108 def descr__enter__(self, space):
109 self.descr_lock_acquire(space)
110 return self
111
112 def descr__exit__(self, space, __args__):
113 self.descr_lock_release(space)
114
115 def __enter__(self):
116 self.descr_lock_acquire(self.space)
117 return self
118
119 def __exit__(self, *args):
120 self.descr_lock_release(self.space)
121
122 def descr__repr__(self, space):
123 classname = space.getfulltypename(self)
124 if self._is_locked():
125 locked = "locked"
126 else:
127 locked = "unlocked"
128 return self.getrepr(space, '%s %s object' % (locked, classname))
129
130 def descr_at_fork_reinit(self, space):
131 # XXX this it not good enough! CPython leaks the underlying lock
132 self.__init__(space)
133
134
135 Lock.typedef = TypeDef(
136 "_thread.lock",
137 __doc__="""\
138 A lock object is a synchronization primitive. To create a lock,
139 call the thread.allocate_lock() function. Methods are:
140
141 acquire() -- lock the lock, possibly blocking until it can be obtained
142 release() -- unlock of the lock
143 locked() -- test whether the lock is currently locked
144
145 A lock is not owned by the thread that locked it; another thread may
146 unlock it. A thread attempting to lock a lock that it has already locked
147 will block until another thread unlocks it. Deadlocks may ensue.""",
148 acquire=interp2app(Lock.descr_lock_acquire),
149 release=interp2app(Lock.descr_lock_release),
150 locked=interp2app(Lock.descr_lock_locked),
151 __enter__=interp2app(Lock.descr__enter__),
152 __exit__=interp2app(Lock.descr__exit__),
153 __repr__ = interp2app(Lock.descr__repr__),
154 __weakref__ = make_weakref_descr(Lock),
155 # Obsolete synonyms
156 acquire_lock=interp2app(Lock.descr_lock_acquire),
157 release_lock=interp2app(Lock.descr_lock_release),
158 locked_lock=interp2app(Lock.descr_lock_locked),
159
160 _at_fork_reinit=interp2app(Lock.descr_at_fork_reinit),
161 )
162
163
164 def allocate_lock(space):
165 """Create a new lock object. (allocate() is an obsolete synonym.)
166 See LockType.__doc__ for information about locks."""
167 return Lock(space)
168
169 def _set_sentinel(space):
170 """_set_sentinel() -> lock
171
172 Set a sentinel lock that will be released when the current thread
173 state is finalized (after it is untied from the interpreter).
174
175 This is a private API for the threading module."""
176 # see issue 18808. We need to release this lock just before exiting any thread!
177 ec = space.getexecutioncontext()
178 # after forking the lock must be recreated! forget the old lock
179 lock = Lock(space)
180 ec._sentinel_lock = lock
181 return lock
182
183 class W_RLock(W_Root):
184 def __init__(self, space):
185 self.rlock_count = 0
186 self.rlock_owner = 0
187 try:
188 self.lock = rthread.allocate_lock()
189 except rthread.error:
190 raise wrap_thread_error(space, "cannot allocate lock")
191
192 def descr__new__(space, w_subtype):
193 self = space.allocate_instance(W_RLock, w_subtype)
194 W_RLock.__init__(self, space)
195 return self
196
197 def descr__repr__(self, space):
198 classname = space.getfulltypename(self)
199 if self.rlock_count == 0:
200 locked = "unlocked"
201 else:
202 locked = "locked"
203 return self.getrepr(space, '%s %s object owner=%d count=%d' % (
204 locked, classname, self.rlock_owner, self.rlock_count))
205
206 @unwrap_spec(blocking=int, timeout=float)
207 def acquire_w(self, space, blocking=True, timeout=-1.0):
208 """Lock the lock. `blocking` indicates whether we should wait
209 for the lock to be available or not. If `blocking` is False
210 and another thread holds the lock, the method will return False
211 immediately. If `blocking` is True and another thread holds
212 the lock, the method will wait for the lock to be released,
213 take it and then return True.
214 (note: the blocking operation is not interruptible.)
215
216 In all other cases, the method will return True immediately.
217 Precisely, if the current thread already holds the lock, its
218 internal counter is simply incremented. If nobody holds the lock,
219 the lock is taken and its internal counter initialized to 1."""
220 microseconds = parse_acquire_args(space, blocking, timeout)
221 tid = rthread.get_ident()
222 if self.rlock_count > 0 and tid == self.rlock_owner:
223 try:
224 self.rlock_count = ovfcheck(self.rlock_count + 1)
225 except OverflowError:
226 raise oefmt(space.w_OverflowError,
227 "internal lock count overflowed")
228 return space.w_True
229
230 r = True
231 if self.rlock_count > 0 or not self.lock.acquire(False):
232 if not blocking:
233 return space.w_False
234 r = acquire_timed(space, self.lock, microseconds)
235 r = (r == RPY_LOCK_ACQUIRED)
236 if r:
237 assert self.rlock_count == 0
238 self.rlock_owner = tid
239 self.rlock_count = 1
240
241 return space.newbool(r)
242
243 def release_w(self, space):
244 """Release the lock, allowing another thread that is blocked waiting for
245 the lock to acquire the lock. The lock must be in the locked state,
246 and must be locked by the same thread that unlocks it; otherwise a
247 `RuntimeError` is raised.
248
249 Do note that if the lock was acquire()d several times in a row by the
250 current thread, release() needs to be called as many times for the lock
251 to be available for other threads."""
252 tid = rthread.get_ident()
253 if self.rlock_count == 0 or self.rlock_owner != tid:
254 raise oefmt(space.w_RuntimeError,
255 "cannot release un-acquired lock")
256 self.rlock_count -= 1
257 if self.rlock_count == 0:
258 self.rlock_owner = 0
259 self.lock.release()
260
261 def recursion_count(self, space):
262 """_recursion_count() -> int
263
264 For internal use by reentrancy checks."""
265
266 tid = rthread.get_ident()
267 if self.rlock_owner == tid:
268 return space.newint(self.rlock_count)
269 return space.newint(0)
270
271 def is_owned_w(self, space):
272 """For internal use by `threading.Condition`."""
273 tid = rthread.get_ident()
274 if self.rlock_count > 0 and self.rlock_owner == tid:
275 return space.w_True
276 else:
277 return space.w_False
278
279 def acquire_restore_w(self, space, w_saved_state):
280 """For internal use by `threading.Condition`."""
281 # saved_state is the value returned by release_save()
282 w_count, w_owner = space.unpackiterable(w_saved_state, 2)
283 count = space.int_w(w_count)
284 owner = space.int_w(w_owner)
285 r = True
286 if not self.lock.acquire(False):
287 r = self.lock.acquire(True)
288 if not r:
289 raise wrap_thread_error(space, "could not acquire lock")
290 assert self.rlock_count == 0
291 self.rlock_owner = owner
292 self.rlock_count = count
293
294 def release_save_w(self, space):
295 """For internal use by `threading.Condition`."""
296 if self.rlock_count == 0:
297 raise oefmt(space.w_RuntimeError,
298 "cannot release un-acquired lock")
299 count, self.rlock_count = self.rlock_count, 0
300 owner, self.rlock_owner = self.rlock_owner, 0
301 self.lock.release()
302 return space.newtuple2(space.newint(count), space.newint(owner))
303
304 def descr__enter__(self, space):
305 self.acquire_w(space)
306 return self
307
308 def descr__exit__(self, space, __args__):
309 self.release_w(space)
310
311 def descr_at_fork_reinit(self, space):
312 # XXX not good enough, cpython leaks the OS lock
313 self.__init__(space)
314
315
316 W_RLock.typedef = TypeDef(
317 "_thread.RLock",
318 __new__ = interp2app(W_RLock.descr__new__.im_func),
319 acquire = interp2app(W_RLock.acquire_w),
320 release = interp2app(W_RLock.release_w),
321 _recursion_count = interp2app(W_RLock.recursion_count),
322 _is_owned = interp2app(W_RLock.is_owned_w),
323 _acquire_restore = interp2app(W_RLock.acquire_restore_w),
324 _release_save = interp2app(W_RLock.release_save_w),
325 __enter__ = interp2app(W_RLock.descr__enter__),
326 __exit__ = interp2app(W_RLock.descr__exit__),
327 __weakref__ = make_weakref_descr(W_RLock),
328 __repr__ = interp2app(W_RLock.descr__repr__),
329 _at_fork_reinit = interp2app(W_RLock.descr_at_fork_reinit),
330 )