Debian Codegraph @

pypy/module/thread/os_thread.py

raw symbols SCIP
1 """
2 Thread support based on OS-level threads.
3 """
4
5 import os
6 from signal import SIGINT
7 from rpython.rlib import rthread
8 from pypy.module.thread.error import wrap_thread_error
9 from pypy.module.signal.interp_signal import check_signum_in_range
10 from pypy.interpreter.error import OperationError, oefmt
11 from pypy.interpreter.gateway import unwrap_spec, Arguments
12
13 # Here are the steps performed to start a new thread:
14 #
15 # * The bootstrapper.lock is first acquired to prevent two parallel
16 # starting threads from messing with each other's start-up data.
17 #
18 # * The start-up data (the app-level callable and arguments) is
19 # stored in the global bootstrapper object.
20 #
21 # * The new thread is launched at RPython level using an rffi call
22 # to the C function RPyThreadStart() defined in
23 # translator/c/src/thread*.h. This RPython thread will invoke the
24 # static method bootstrapper.bootstrap() as a call-back.
25 #
26 # * As if it was a regular callback, rffi adds a wrapper around
27 # bootstrap(). This wrapper acquires and releases the GIL. In this
28 # way the new thread is immediately GIL-protected.
29 #
30 # * As soon as the GIL is acquired in the new thread, the gc_thread_run()
31 # operation is called (this is all done by gil.after_external_call(),
32 # called from the rffi-generated wrapper). The gc_thread_run()
33 # operation will automatically notice that the current thread id was
34 # not seen before, and (in shadowstack) it will allocate and use a
35 # fresh new stack.
36 #
37 # * Only then does bootstrap() really run. The first thing it does
38 # is grab the start-up information (app-level callable and args)
39 # out of the global bootstrapper object and release bootstrapper.lock.
40 # Then it calls the app-level callable, to actually run the thread.
41 #
42 # * After each potential thread switch, as soon as the GIL is re-acquired,
43 # gc_thread_run() is called again; it ensures that the currently
44 # installed shadow stack is the correct one for the currently running
45 # thread.
46 #
47 # * Just before a thread finishes, gc_thread_die() is called to free
48 # its shadow stack.
49
50
51 class Bootstrapper(object):
52 "A global container used to pass information to newly starting threads."
53
54 # Passing a closure argument to rthread.start_new_thread() would be
55 # theoretically nicer, but comes with messy memory management issues.
56 # This is much more straightforward.
57
58 nbthreads = 0
59
60 # The following lock is held whenever the fields
61 # 'bootstrapper.w_callable' and 'bootstrapper.args' are in use.
62 lock = None
63 args = None
64 w_callable = None
65
66 @staticmethod
67 def setup(space):
68 if bootstrapper.lock is None:
69 try:
70 bootstrapper.lock = rthread.allocate_lock()
71 except rthread.error:
72 raise wrap_thread_error(space, "can't allocate bootstrap lock")
73
74 @staticmethod
75 def reinit():
76 bootstrapper.lock = None
77 bootstrapper.nbthreads = 0
78 bootstrapper.w_callable = None
79 bootstrapper.args = None
80
81 def _cleanup_(self):
82 self.reinit()
83
84 def bootstrap():
85 # Note that when this runs, we already hold the GIL. This is ensured
86 # by rffi's callback mecanism: we are a callback for the
87 # c_thread_start() external function.
88 rthread.gc_thread_start()
89 space = bootstrapper.space
90 w_callable = bootstrapper.w_callable
91 args = bootstrapper.args
92 bootstrapper.nbthreads += 1
93 bootstrapper.release()
94 # run!
95 try:
96 bootstrapper.run(space, w_callable, args)
97 # done
98 except Exception as e:
99 # oups! last-level attempt to recover.
100 try:
101 STDERR = 2
102 os.write(STDERR, "Thread exited with ")
103 os.write(STDERR, str(e))
104 os.write(STDERR, "\n")
105 except OSError:
106 pass
107 #
108 bootstrapper.nbthreads -= 1
109 rthread.gc_thread_die()
110 bootstrap = staticmethod(bootstrap)
111
112 def acquire(space, w_callable, args):
113 # If the previous thread didn't start yet, wait until it does.
114 # Note that bootstrapper.lock must be a regular lock, not a NOAUTO
115 # lock, because the GIL must be released while we wait.
116 bootstrapper.lock.acquire(True)
117 bootstrapper.space = space
118 bootstrapper.w_callable = w_callable
119 bootstrapper.args = args
120 acquire = staticmethod(acquire)
121
122 def release():
123 # clean up 'bootstrapper' to make it ready for the next
124 # start_new_thread() and release the lock to tell that there
125 # isn't any bootstrapping thread left.
126 bootstrapper.w_callable = None
127 bootstrapper.args = None
128 bootstrapper.lock.release()
129 release = staticmethod(release)
130
131 def run(space, w_callable, args):
132 # add the ExecutionContext to space.threadlocals
133 space.threadlocals.enter_thread(space)
134 try:
135 space.call_args(w_callable, args)
136 except OperationError as e:
137 if not e.match(space, space.w_SystemExit):
138 ident = rthread.get_ident()
139 # PyPy adds the thread ident
140 where = 'in thread %d started by ' % ident
141 e.write_unraisable(space, where, w_callable, with_traceback=True)
142 e.clear(space)
143 # clean up space.threadlocals to remove the ExecutionContext
144 # entry corresponding to the current thread
145 space.threadlocals.leave_thread(space)
146 run = staticmethod(run)
147
148 bootstrapper = Bootstrapper()
149
150
151 def setup_threads(space):
152 space.threadlocals.setup_threads(space)
153 bootstrapper.setup(space)
154
155 def threads_initialized(space):
156 return space.threadlocals.threads_initialized()
157
158
159 def reinit_threads(space):
160 "Called in the child process after a fork()"
161 space.threadlocals.reinit_threads(space)
162 bootstrapper.reinit()
163 rthread.thread_after_fork()
164
165 def start_new_thread(space, w_callable, w_args, w_kwargs=None):
166 """Start a new thread and return its identifier. The thread will call the
167 function with positional arguments from the tuple args and keyword arguments
168 taken from the optional dictionary kwargs. The thread exits when the
169 function returns; the return value is ignored. The thread will also exit
170 when the function raises an unhandled exception; a stack trace will be
171 printed unless the exception is SystemExit."""
172 setup_threads(space)
173 if not space.isinstance_w(w_args, space.w_tuple):
174 raise oefmt(space.w_TypeError, "2nd arg must be a tuple")
175 if w_kwargs is not None and not space.isinstance_w(w_kwargs, space.w_dict):
176 raise oefmt(space.w_TypeError, "optional 3rd arg must be a dictionary")
177 if not space.is_true(space.callable(w_callable)):
178 raise oefmt(space.w_TypeError, "first arg must be callable")
179
180 args = Arguments.frompacked(space, w_args, w_kwargs)
181 bootstrapper.acquire(space, w_callable, args)
182 try:
183 try:
184 ident = rthread.start_new_thread(bootstrapper.bootstrap, ())
185 except Exception:
186 bootstrapper.release() # normally called by the new thread
187 raise
188 except rthread.error:
189 raise wrap_thread_error(space, "can't start new thread")
190 return space.newint(ident)
191
192
193 def get_ident(space):
194 """Return a non-zero integer that uniquely identifies the current thread
195 amongst other threads that exist simultaneously.
196 This may be used to identify per-thread resources.
197 Even though on some platforms threads identities may appear to be
198 allocated consecutive numbers starting at 1, this behavior should not
199 be relied upon, and the number should be seen purely as a magic cookie.
200 A thread's identity may be reused for another thread after it exits."""
201 ident = rthread.get_ident()
202 return space.newint_from_size_t(ident)
203
204 def get_native_id(space):
205 """Return the native integral Thread ID of the current thread assigned by
206 the kernel. This is a non-negative integer. Its value may be used to uniquely
207 identify this particular thread system-wide (until the thread terminates, after
208 which the value may be recycled by the OS)."""
209 native_id = rthread.c_get_native_id()
210 return space.newint(native_id)
211
212
213
214
215
216 @unwrap_spec(size=int)
217 def stack_size(space, size=0):
218 """stack_size([size]) -> size
219
220 Return the thread stack size used when creating new threads. The
221 optional size argument specifies the stack size (in bytes) to be used
222 for subsequently created threads, and must be 0 (use platform or
223 configured default) or a positive integer value of at least 32,768 (32k).
224 If changing the thread stack size is unsupported, a ThreadError
225 exception is raised. If the specified size is invalid, a ValueError
226 exception is raised, and the stack size is unmodified. 32k bytes
227 is currently the minimum supported stack size value to guarantee
228 sufficient stack space for the interpreter itself.
229
230 Note that some platforms may have particular restrictions on values for
231 the stack size, such as requiring a minimum stack size larger than 32kB or
232 requiring allocation in multiples of the system memory page size
233 - platform documentation should be referred to for more information
234 (4kB pages are common; using multiples of 4096 for the stack size is
235 the suggested approach in the absence of more specific information)."""
236 if size < 0:
237 raise oefmt(space.w_ValueError, "size must be 0 or a positive value")
238 old_size = rthread.get_stacksize()
239 error = rthread.set_stacksize(size)
240 if error == -1:
241 raise oefmt(space.w_ValueError, "size not valid: %d bytes", size)
242 if error == -2:
243 raise wrap_thread_error(space, "setting stack size not supported")
244 return space.newint(old_size)
245
246 def _count(space):
247 """_count() -> integer
248 Return the number of currently running Python threads, excluding
249 the main thread. The returned number comprises all threads created
250 through `start_new_thread()` as well as `threading.Thread`, and not
251 yet finished.
252
253 This function is meant for internal and specialized purposes only.
254 In most applications `threading.enumerate()` should be used instead."""
255 return space.newint(bootstrapper.nbthreads)
256
257 def exit(space):
258 """This is synonymous to ``raise SystemExit''. It will cause the current
259 thread to exit silently unless the exception is caught."""
260 raise OperationError(space.w_SystemExit, space.w_None)
261
262 @unwrap_spec(signum=int)
263 def interrupt_main(space, signum=SIGINT):
264 """interrupt_main(signum=signal.sigint)
265
266 Simulate the arrival of the given signal in the main thread,
267 where the corresponding signal handler will be executed.
268 If *signum* is omitted, SIGINT is assumed.
269 A subthread can use this function to interrupt the main thread.
270
271 Note: the default signal handler for SIGINT raises ``KeyboardInterrupt``."""
272 if space.check_signal_action is None: # no signal module!
273 raise OperationError(space.w_KeyboardInterrupt, space.w_None)
274 check_signum_in_range(space, signum)
275 space.check_signal_action.set_interrupt(signum)