Debian Codegraph @

rpython/rlib/rthread.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import rffi, lltype, llmemory
2 from rpython.translator.tool.cbuild import ExternalCompilationInfo
3 from rpython.translator import cdir
4 import py, sys
5 from rpython.rlib import jit, rgc
6 from rpython.rlib.debug import ll_assert
7 from rpython.rlib.objectmodel import we_are_translated, specialize
8 from rpython.rlib.objectmodel import CDefinedIntSymbolic, not_rpython
9 from rpython.rtyper.lltypesystem.lloperation import llop
10 from rpython.rtyper.tool import rffi_platform
11 from rpython.rtyper.extregistry import ExtRegistryEntry
12
13 class RThreadError(Exception):
14 pass
15 error = RThreadError
16
17 translator_c_dir = py.path.local(cdir)
18
19 eci = ExternalCompilationInfo(
20 includes = ['src/thread.h'],
21 separate_module_files = [translator_c_dir / 'src' / 'thread.c'],
22 include_dirs = [translator_c_dir],
23 )
24
25 class CConfig:
26 _compilation_info_ = eci
27 RPYTHREAD_NAME = rffi_platform.DefinedConstantString('RPYTHREAD_NAME')
28 USE_SEMAPHORES = rffi_platform.Defined('USE_SEMAPHORES')
29 CS_GNU_LIBPTHREAD_VERSION = rffi_platform.DefinedConstantInteger(
30 '_CS_GNU_LIBPTHREAD_VERSION')
31 cconfig = rffi_platform.configure(CConfig)
32 globals().update(cconfig)
33
34
35 def llexternal(name, args, result, **kwds):
36 kwds.setdefault('sandboxsafe', True)
37 return rffi.llexternal(name, args, result, compilation_info=eci,
38 **kwds)
39
40 @not_rpython
41 def _emulated_start_new_thread(func):
42 import thread
43 try:
44 ident = thread.start_new_thread(func, ())
45 except thread.error:
46 ident = -1
47 return rffi.cast(lltype.Signed, ident)
48
49 CALLBACK = lltype.Ptr(lltype.FuncType([], lltype.Void))
50 c_thread_start = llexternal('RPyThreadStart', [CALLBACK], lltype.Signed,
51 _callable=_emulated_start_new_thread,
52 releasegil=True) # release the GIL, but most
53 # importantly, reacquire it
54 # around the callback
55
56 c_pthread_kill = llexternal('RPyThread_kill', [lltype.Signed, rffi.INT], rffi.INT,
57 save_err=rffi.RFFI_SAVE_ERRNO)
58
59 TLOCKP = rffi.COpaquePtr('struct RPyOpaque_ThreadLock',
60 compilation_info=eci)
61 TLOCKP_SIZE = rffi_platform.sizeof('struct RPyOpaque_ThreadLock', eci)
62 c_thread_lock_init = llexternal('RPyThreadLockInit', [TLOCKP], rffi.INT,
63 releasegil=False) # may add in a global list
64 c_thread_lock_dealloc_NOAUTO = llexternal('RPyOpaqueDealloc_ThreadLock',
65 [TLOCKP], lltype.Void,
66 _nowrapper=True)
67 c_thread_acquirelock = llexternal('RPyThreadAcquireLock', [TLOCKP, rffi.INT],
68 rffi.INT,
69 releasegil=True) # release the GIL
70 c_thread_acquirelock_timed = llexternal('RPyThreadAcquireLockTimed',
71 [TLOCKP, rffi.LONGLONG, rffi.INT],
72 rffi.INT,
73 releasegil=True) # release the GIL
74 c_thread_releaselock = llexternal('RPyThreadReleaseLock', [TLOCKP],
75 lltype.Signed,
76 _nowrapper=True) # *don't* release the GIL
77
78 # another set of functions, this time in versions that don't cause the
79 # GIL to be released. Used to be there to handle the GIL lock itself,
80 # but that was changed (see rgil.py). Now here for performance only.
81 c_thread_acquirelock_NOAUTO = llexternal('RPyThreadAcquireLock',
82 [TLOCKP, rffi.INT], rffi.INT,
83 _nowrapper=True)
84 c_thread_acquirelock_timed_NOAUTO = llexternal('RPyThreadAcquireLockTimed',
85 [TLOCKP, rffi.LONGLONG, rffi.INT],
86 rffi.INT, _nowrapper=True)
87 c_thread_releaselock_NOAUTO = c_thread_releaselock
88
89 c_get_native_id = llexternal('RPyThread_get_thread_native_id', [],
90 rffi.ULONG, _nowrapper=True)
91
92 def allocate_lock():
93 # Add some memory pressure for the size of the lock because it is an
94 # Opaque object
95 lock = Lock(allocate_ll_lock())
96 rgc.add_memory_pressure(TLOCKP_SIZE, lock)
97 return lock
98
99 @specialize.arg(0)
100 def ll_start_new_thread(func):
101 from rpython.rlib import rgil
102 _check_thread_enabled()
103 rgil.allocate()
104 # ^^^ convenience: any RPython program which uses explicitly
105 # rthread.start_new_thread() will initialize the GIL at that
106 # point.
107 ident = c_thread_start(func)
108 if ident == -1:
109 raise error("can't start new thread")
110 return ident
111
112 # wrappers...
113
114 def get_ident():
115 if we_are_translated():
116 return tlfield_thread_ident.getraw()
117 else:
118 try:
119 import thread
120 except ImportError:
121 return 42
122 return thread.get_ident()
123
124 def get_or_make_ident():
125 if we_are_translated():
126 return tlfield_thread_ident.get_or_make_raw()
127 else:
128 return get_ident()
129
130 @specialize.arg(0)
131 def start_new_thread(x, y):
132 """In RPython, no argument can be passed. You have to use global
133 variables to pass information to the new thread. That's not very
134 nice, but at least it avoids some levels of GC issues.
135 """
136 assert len(y) == 0
137 return ll_start_new_thread(x)
138
139 class DummyLock(object):
140 def acquire(self, flag):
141 return True
142
143 def is_acquired(self):
144 return False
145
146 def release(self):
147 pass
148
149 def _freeze_(self):
150 return True
151
152 def __enter__(self):
153 pass
154
155 def __exit__(self, *args):
156 pass
157
158 dummy_lock = DummyLock()
159
160 class Lock(object):
161 """ Container for low-level implementation
162 of a lock object
163 """
164 _immutable_fields_ = ["_lock"]
165
166 def __init__(self, ll_lock):
167 self._lock = ll_lock
168
169 def acquire(self, flag):
170 if flag:
171 res = c_thread_acquirelock(self._lock, 1)
172 if rffi.cast(lltype.Signed, res) != 1:
173 raise error("lock acquire returned an unexpected error")
174 return True
175 else:
176 res = c_thread_acquirelock_timed_NOAUTO(
177 self._lock,
178 rffi.cast(rffi.LONGLONG, 0),
179 rffi.cast(rffi.INT, 0))
180 res = rffi.cast(lltype.Signed, res)
181 return bool(res)
182
183 def is_acquired(self):
184 """ check if the lock is acquired (does not release the GIL) """
185 res = c_thread_acquirelock_timed_NOAUTO(
186 self._lock,
187 rffi.cast(rffi.LONGLONG, 0),
188 rffi.cast(rffi.INT, 0))
189 res = rffi.cast(lltype.Signed, res)
190 return not bool(res)
191
192 def acquire_timed(self, timeout):
193 """Timeout is in microseconds. Returns 0 in case of failure,
194 1 in case it works, 2 if interrupted by a signal."""
195 res = c_thread_acquirelock_timed(self._lock, timeout, 1)
196 res = rffi.cast(lltype.Signed, res)
197 return res
198
199 def release(self):
200 if c_thread_releaselock(self._lock) != 0:
201 raise error("the lock was not previously acquired")
202
203 def __del__(self):
204 if free_ll_lock is None: # happens when tests are shutting down
205 return
206 free_ll_lock(self._lock)
207
208 def __enter__(self):
209 self.acquire(True)
210
211 def __exit__(self, *args):
212 self.release()
213
214 def _cleanup_(self):
215 raise Exception("seeing a prebuilt rpython.rlib.rthread.Lock instance")
216
217 def _check_thread_enabled():
218 pass
219 class Entry(ExtRegistryEntry):
220 _about_ = _check_thread_enabled
221 def compute_result_annotation(self):
222 translator = self.bookkeeper.annotator.translator
223 if not translator.config.translation.thread:
224 raise Exception(
225 "this RPython program uses threads: translate with '--thread'")
226 def specialize_call(self, hop):
227 hop.exception_cannot_occur()
228
229 # ____________________________________________________________
230 #
231 # Stack size
232
233 get_stacksize = llexternal('RPyThreadGetStackSize', [], lltype.Signed)
234 set_stacksize = llexternal('RPyThreadSetStackSize', [lltype.Signed],
235 lltype.Signed)
236
237 # ____________________________________________________________
238 #
239 # Hack
240
241 thread_after_fork = llexternal('RPyThreadAfterFork', [], lltype.Void)
242
243 # ____________________________________________________________
244 #
245 # GIL support wrappers
246
247 null_ll_lock = lltype.nullptr(TLOCKP.TO)
248
249 def allocate_ll_lock():
250 # track_allocation=False here; be careful to lltype.free() it. The
251 # reason it is set to False is that we get it from all app-level
252 # lock objects, as well as from the GIL, which exists at shutdown.
253 ll_lock = lltype.malloc(TLOCKP.TO, flavor='raw', track_allocation=False)
254 res = rffi.cast(lltype.Signed, c_thread_lock_init(ll_lock))
255 if res <= 0:
256 lltype.free(ll_lock, flavor='raw', track_allocation=False)
257 raise error("out of resources")
258 return ll_lock
259
260 def free_ll_lock(ll_lock):
261 acquire_NOAUTO(ll_lock, False)
262 release_NOAUTO(ll_lock)
263 c_thread_lock_dealloc_NOAUTO(ll_lock)
264 lltype.free(ll_lock, flavor='raw', track_allocation=False)
265
266 def acquire_NOAUTO(ll_lock, flag):
267 flag = rffi.cast(rffi.INT, int(flag))
268 res = c_thread_acquirelock_NOAUTO(ll_lock, flag)
269 res = rffi.cast(lltype.Signed, res)
270 return bool(res)
271
272 def release_NOAUTO(ll_lock):
273 if not we_are_translated():
274 ll_assert(not acquire_NOAUTO(ll_lock, False), "NOAUTO lock not held!")
275 c_thread_releaselock_NOAUTO(ll_lock)
276
277 # ____________________________________________________________
278 #
279 # Thread integration.
280 # These are five completely ad-hoc operations at the moment.
281
282 @jit.dont_look_inside
283 def gc_thread_run():
284 """To call whenever the current thread (re-)acquired the GIL.
285 """
286 if we_are_translated():
287 llop.gc_thread_run(lltype.Void)
288 gc_thread_run._always_inline_ = True
289
290 @jit.dont_look_inside
291 def gc_thread_start():
292 """To call at the beginning of a new thread.
293 """
294 if we_are_translated():
295 llop.gc_thread_start(lltype.Void)
296
297 @jit.dont_look_inside
298 def gc_thread_die():
299 """To call just before the final GIL release done by a dying
300 thread. After a thread_die(), no more gc operation should
301 occur in this thread.
302 """
303 if we_are_translated():
304 llop.gc_thread_die(lltype.Void)
305 gc_thread_die._always_inline_ = True
306
307 @jit.dont_look_inside
308 def gc_thread_before_fork():
309 """To call just before fork(). Prepares for forking, after
310 which only the current thread will be alive.
311 """
312 if we_are_translated():
313 return llop.gc_thread_before_fork(llmemory.Address)
314 else:
315 return llmemory.NULL
316
317 @jit.dont_look_inside
318 def gc_thread_after_fork(result_of_fork, opaqueaddr):
319 """To call just after fork().
320 """
321 if we_are_translated():
322 llop.gc_thread_after_fork(lltype.Void, result_of_fork, opaqueaddr)
323 else:
324 assert opaqueaddr == llmemory.NULL
325
326 # ____________________________________________________________
327 #
328 # Thread-locals.
329
330
331 class ThreadLocalField(object):
332 @not_rpython
333 def __init__(self, FIELDTYPE, fieldname, loop_invariant=False):
334 "must be prebuilt"
335 try:
336 from thread import _local
337 except ImportError:
338 class _local(object):
339 pass
340 self.FIELDTYPE = FIELDTYPE
341 self.fieldname = fieldname
342 self.local = _local() # <- not rpython
343 zero = rffi.cast(FIELDTYPE, 0)
344 offset = CDefinedIntSymbolic('RPY_TLOFS_%s' % self.fieldname,
345 default='?')
346 offset.loop_invariant = loop_invariant
347 self._offset = offset
348
349 def getraw():
350 if we_are_translated():
351 _threadlocalref_seeme(self)
352 return llop.threadlocalref_get(FIELDTYPE, offset)
353 else:
354 return getattr(self.local, 'rawvalue', zero)
355
356 @jit.dont_look_inside
357 def get_or_make_raw():
358 if we_are_translated():
359 _threadlocalref_seeme(self)
360 return llop.threadlocalref_load(FIELDTYPE, offset)
361 else:
362 return getattr(self.local, 'rawvalue', zero)
363
364 @jit.dont_look_inside
365 def setraw(value):
366 if we_are_translated():
367 _threadlocalref_seeme(self)
368 llop.threadlocalref_store(lltype.Void, offset, value)
369 else:
370 self.local.rawvalue = value
371
372 def getoffset():
373 _threadlocalref_seeme(self)
374 return offset
375
376 self.getraw = getraw
377 self.get_or_make_raw = get_or_make_raw
378 self.setraw = setraw
379 self.getoffset = getoffset
380
381 def _freeze_(self):
382 return True
383
384
385 class ThreadLocalReference(ThreadLocalField):
386 # A thread-local that points to an object. The object stored in such
387 # a thread-local is kept alive as long as the thread is not finished
388 # (but only with our own GCs! it seems not to work with Boehm...)
389 # (also, on Windows, if you're not making a DLL but an EXE, it will
390 # leak the objects when a thread finishes; see threadlocal.c.)
391 _COUNT = 1
392
393 @not_rpython
394 def __init__(self, Cls, loop_invariant=False):
395 "must be prebuilt"
396 self.Cls = Cls
397 unique_id = ThreadLocalReference._COUNT
398 ThreadLocalReference._COUNT += 1
399 ThreadLocalField.__init__(self, lltype.Signed, 'tlref%d' % unique_id,
400 loop_invariant=loop_invariant)
401 offset = self._offset
402
403 def get():
404 if we_are_translated():
405 from rpython.rtyper import rclass
406 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
407 _threadlocalref_seeme(self)
408 ptr = llop.threadlocalref_get(rclass.OBJECTPTR, offset)
409 return cast_base_ptr_to_instance(Cls, ptr)
410 else:
411 return getattr(self.local, 'value', None)
412
413 @jit.dont_look_inside
414 def set(value):
415 assert isinstance(value, Cls) or value is None
416 if we_are_translated():
417 from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
418 ptr = cast_instance_to_base_ptr(value)
419 _threadlocalref_seeme(self)
420 llop.threadlocalref_store(lltype.Void, offset, ptr)
421 rgc.register_custom_trace_hook(TRACETLREF, _lambda_trace_tlref)
422 rgc.ll_writebarrier(_tracetlref_obj)
423 else:
424 self.local.value = value
425
426 self.get = get
427 self.set = set
428
429 def _trace_tlref(gc, obj, callback, arg1, arg2):
430 p = llmemory.NULL
431 llop.threadlocalref_acquire(lltype.Void)
432 while True:
433 p = llop.threadlocalref_enum(llmemory.Address, p)
434 if not p:
435 break
436 gc._trace_callback(callback, arg1, arg2, p + offset)
437 llop.threadlocalref_release(lltype.Void)
438 _lambda_trace_tlref = lambda: _trace_tlref
439 # WAAAH obscurity: can't use a name that may be non-unique,
440 # otherwise the types compare equal, even though we call
441 # register_custom_trace_hook() to register different trace
442 # functions...
443 TRACETLREF = lltype.GcStruct('TRACETLREF%d' % unique_id)
444 _tracetlref_obj = lltype.malloc(TRACETLREF, immortal=True)
445
446 @staticmethod
447 def automatic_keepalive(config):
448 """Returns True if translated with a GC that keeps alive
449 the set() value until the end of the thread. Returns False
450 if you need to keep it alive yourself (but in that case, you
451 should also reset it to None before the thread finishes).
452 """
453 return (config.translation.gctransformer == "framework" and
454 # see translator/c/src/threadlocal.c for the following line
455 (not _win32 or config.translation.shared))
456
457
458 tlfield_thread_ident = ThreadLocalField(lltype.Signed, "thread_ident",
459 loop_invariant=True)
460 tlfield_p_errno = ThreadLocalField(rffi.CArrayPtr(rffi.INT_real), "p_errno",
461 loop_invariant=True)
462 tlfield_rpy_errno = ThreadLocalField(rffi.INT, "rpy_errno")
463 tlfield_alt_errno = ThreadLocalField(rffi.INT, "alt_errno")
464 _win32 = (sys.platform == "win32")
465 if _win32:
466 from rpython.rlib import rwin32
467 tlfield_rpy_lasterror = ThreadLocalField(rwin32.DWORD, "rpy_lasterror")
468 tlfield_alt_lasterror = ThreadLocalField(rwin32.DWORD, "alt_lasterror")
469
470 @not_rpython
471 def _threadlocalref_seeme(field):
472 pass
473
474 class _Entry(ExtRegistryEntry):
475 _about_ = _threadlocalref_seeme
476
477 def compute_result_annotation(self, s_field):
478 field = s_field.const
479 self.bookkeeper.thread_local_fields.add(field)
480
481 def specialize_call(self, hop):
482 hop.exception_cannot_occur()