| 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 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
class Bootstrapper(object): |
| 52 |
"A global container used to pass information to newly starting threads." |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
nbthreads = 0 |
| 59 |
|
| 60 |
|
| 61 |
|
| 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 |
|
| 86 |
|
| 87 |
|
| 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 |
|
| 95 |
try: |
| 96 |
bootstrapper.run(space, w_callable, args) |
| 97 |
|
| 98 |
except Exception as e: |
| 99 |
|
| 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 |
|
| 114 |
|
| 115 |
|
| 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 |
|
| 124 |
|
| 125 |
|
| 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 |
|
| 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 |
|
| 140 |
where = 'in thread %d started by ' % ident |
| 141 |
e.write_unraisable(space, where, w_callable, with_traceback=True) |
| 142 |
e.clear(space) |
| 143 |
|
| 144 |
|
| 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() |
| 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: |
| 273 |
raise OperationError(space.w_KeyboardInterrupt, space.w_None) |
| 274 |
check_signum_in_range(space, signum) |
| 275 |
space.check_signal_action.set_interrupt(signum) |