Debian Codegraph @

pypy/module/cpyext/test/test_pystate.py

raw symbols SCIP
1 import py, pytest
2 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
3 from pypy.module.cpyext.test.test_api import BaseApiTest
4 from rpython.rtyper.lltypesystem.lltype import nullptr
5 from pypy.module.cpyext.pystate import PyInterpreterState, PyThreadState
6 from pypy.module.cpyext.pyobject import from_ref
7 from rpython.rtyper.lltypesystem import lltype
8 from pypy.module.cpyext.test.test_cpyext import LeakCheckingTest, freeze_refcnts
9 from pypy.module.cpyext.pystate import PyThreadState_Get, PyInterpreterState_Head
10 from rpython.tool import leakfinder
11
12 class AppTestThreads(AppTestCpythonExtensionBase):
13 def test_allow_threads(self):
14 module = self.import_extension('foo', [
15 ("test", "METH_NOARGS",
16 """
17 Py_BEGIN_ALLOW_THREADS
18 {
19 Py_BLOCK_THREADS
20 Py_UNBLOCK_THREADS
21 }
22 Py_END_ALLOW_THREADS
23 Py_RETURN_NONE;
24 """),
25 ])
26 # Should compile at least
27 module.test()
28
29 def test_gilstate(self):
30 module = self.import_extension('foo', [
31 ("double_ensure", "METH_O",
32 '''
33 PyGILState_STATE state0, state1;
34 int val = PyLong_AsLong(args);
35 PyEval_InitThreads();
36 state0 = PyGILState_Ensure(); /* hangs here */
37 if (val != 0)
38 {
39 state1 = PyGILState_Ensure();
40 PyGILState_Release(state1);
41 }
42 PyGILState_Release(state0);
43 Py_RETURN_NONE;
44 '''),
45 ])
46 module.double_ensure(0)
47 module.double_ensure(1)
48
49 def test_finalizing(self):
50 module = self.import_extension('foo', [
51 ("get", "METH_NOARGS",
52 """
53 if (_Py_Finalizing) {
54 return PyLong_FromLong(0);
55 }
56 if (_Py_Finalizing != NULL) {
57 return PyLong_FromLong(1);
58 }
59 if (_Py_IsFinalizing()) {
60 return PyLong_FromLong(2);
61 }
62 return PyLong_FromLong(3);
63 """),
64 ])
65 assert module.get() == 3
66
67 def test_thread_state_get(self):
68 module = self.import_extension('foo', [
69 ("get", "METH_NOARGS",
70 """
71 PyThreadState *tstate = PyThreadState_Get();
72 if (tstate == NULL) {
73 return PyLong_FromLong(0);
74 }
75 PyInterpreterState *interp = PyThreadState_GetInterpreter(tstate);
76 if (interp != PyInterpreterState_Head()) {
77 return PyLong_FromLong(1);
78 }
79 if (PyInterpreterState_Next(interp) != NULL) {
80 return PyLong_FromLong(2);
81 }
82 if (tstate != _PyThreadState_UncheckedGet()) {
83 return PyLong_FromLong(4);
84 }
85 if (tstate != PyGILState_GetThisThreadState()) {
86 return PyLong_FromLong(8);
87 }
88 int64_t id = PyThreadState_GetID(tstate);
89 return PyLong_FromLong(id + 100);
90 """),
91 ])
92 assert module.get() > 100
93
94 @py.test.mark.xfail(run=False, reason='PyThreadState_Get() segfaults on py3k and CPython')
95 def test_basic_threadstate_dance(self):
96 module = self.import_extension('foo', [
97 ("dance", "METH_NOARGS",
98 """
99 PyThreadState *old_tstate, *new_tstate;
100 PyObject *d;
101
102 PyEval_InitThreads();
103
104 old_tstate = PyThreadState_Swap(NULL);
105 if (old_tstate == NULL) {
106 return PyLong_FromLong(0);
107 }
108
109 d = PyThreadState_GetDict(); /* fails on cpython */
110 if (d != NULL) {
111 return PyLong_FromLong(1);
112 }
113
114 new_tstate = PyThreadState_Swap(old_tstate);
115 if (new_tstate != NULL) {
116 return PyLong_FromLong(2);
117 }
118
119 new_tstate = PyThreadState_Get();
120 if (new_tstate != old_tstate) {
121 return PyLong_FromLong(3);
122 }
123
124 return PyLong_FromLong(4);
125 """),
126 ])
127 assert module.dance() == 4
128
129 def test_threadstate_dict(self):
130 module = self.import_extension('foo', [
131 ("getdict", "METH_NOARGS",
132 """
133 PyObject *dict = PyThreadState_GetDict();
134 Py_INCREF(dict);
135 return dict;
136 """),
137 ])
138 assert isinstance(module.getdict(), dict)
139
140 def test_savethread(self):
141 module = self.import_extension('foo', [
142 ("bounce", "METH_NOARGS",
143 """
144 PyThreadState * tstate;
145 if (PyEval_ThreadsInitialized() == 0)
146 {
147 PyEval_InitThreads();
148 }
149 PyGILState_Ensure();
150 tstate = PyEval_SaveThread();
151 if (tstate == NULL) {
152 return PyLong_FromLong(0);
153 }
154
155 PyEval_RestoreThread(tstate);
156
157 if (PyThreadState_Get() != tstate) {
158 return PyLong_FromLong(2);
159 }
160
161 return PyLong_FromLong(3);
162 """),
163 ])
164 res = module.bounce()
165 assert res == 3
166
167 def test_thread_and_gil(self):
168 module = self.import_extension('foo', [
169 ("bounce", "METH_NOARGS",
170 """
171 PyThreadState * tstate;
172 PyObject *dict;
173 PyGILState_STATE gilstate;
174
175 if (PyEval_ThreadsInitialized() == 0)
176 {
177 PyEval_InitThreads();
178 }
179 tstate = PyEval_SaveThread();
180 if (tstate == NULL) {
181 return PyLong_FromLong(0);
182 }
183 if (PyGILState_Check() != 0)
184 return PyLong_FromLong(-1);
185 dict = PyThreadState_GetDict();
186 if (dict != NULL) {
187 return PyLong_FromLong(1);
188 }
189 gilstate = PyGILState_Ensure();
190 dict = PyThreadState_GetDict();
191 if (dict == NULL) {
192 return PyLong_FromLong(2);
193 }
194 if (PyGILState_Check() != 1)
195 return PyLong_FromLong(-2);
196 PyGILState_Release(gilstate);
197 if (PyGILState_Check() != 0)
198 return PyLong_FromLong(-3);
199 PyEval_RestoreThread(tstate);
200
201 if (PyThreadState_Get() != tstate) {
202 return PyLong_FromLong(3);
203 }
204 if (PyGILState_Check() != 1)
205 return PyLong_FromLong(-4);
206
207 return PyLong_FromLong(4);
208 """)])
209 res = module.bounce()
210 assert res == 4
211
212 def test_nested_pygilstate_ensure(self):
213 module = self.import_extension('foo', [
214 ("bounce", "METH_NOARGS",
215 """
216 PyGILState_STATE gilstate;
217 PyObject *dict;
218
219 if (PyEval_ThreadsInitialized() == 0)
220 PyEval_InitThreads();
221 dict = PyThreadState_GetDict();
222 gilstate = PyGILState_Ensure();
223 PyGILState_Release(gilstate);
224 if (PyThreadState_GetDict() != dict)
225 return PyLong_FromLong(-2);
226 return PyLong_FromLong(4);
227 """)])
228 res = module.bounce()
229 assert res == 4
230
231 def test_threadsinitialized(self):
232 module = self.import_extension('foo', [
233 ("test", "METH_NOARGS",
234 """
235 return PyLong_FromLong(PyEval_ThreadsInitialized());
236 """),
237 ])
238 res = module.test()
239 assert res in (0, 1)
240
241 def test_thread_interrupt(self):
242 if not self.runappdirect:
243 skip("test fails untranslated for obscure reasons")
244 import signal # to initialize the signal infrastructure
245 import _thread as thread, time
246
247 module = self.import_extension('disruptor', [
248 ("surprise", "METH_VARARGS",
249 """
250 long tid;
251 PyObject *exc;
252 if (!PyArg_ParseTuple(args, "lO", &tid, &exc))
253 return NULL;
254 return PyLong_FromLong(PyThreadState_SetAsyncExc(tid, exc));
255 """),
256 ("nosurprise", "METH_VARARGS",
257 """
258 long tid;
259 if (!PyArg_ParseTuple(args, "l", &tid))
260 return NULL;
261 return PyLong_FromLong(PyThreadState_SetAsyncExc(tid, NULL));
262 """),
263 ])
264 # raise in another thread
265 def f():
266 try:
267 childstarted.append(thread.get_ident())
268 while 1:
269 print("waiting in child")
270 time.sleep(0.1)
271 except KeyError:
272 childstarted.pop()
273 else:
274 thread.interrupt_main() # to crash the test
275 cancelled_exception = False
276
277 for i in range(20):
278 print(i)
279 # first wait for the child to start
280 childstarted = []
281 thread.start_new_thread(f, ())
282 for i in range(500):
283 if childstarted:
284 break
285 time.sleep(0.1)
286 # then interrupt it from the main thread
287 res = module.surprise(childstarted[0], KeyError)
288 assert res == 1
289
290 # try to cancel the interrupt
291 # this is racing! the child could either have been terminated
292 # already or not
293 try:
294 res = module.nosurprise(childstarted[0])
295 assert res in (0, 1)
296 except IndexError:
297 pass
298 else:
299 if res == 1:
300 cancelled_exception = True
301 # actually send exception
302 res = module.surprise(childstarted[0], KeyError)
303 assert res in (0, 1)
304 # now wait for the exception to arrive in the child thread
305 # which empties childstarted again
306 for i in range(500):
307 if not childstarted:
308 break
309 time.sleep(0.1)
310 assert res == 1
311 if self.runappdirect:
312 # only after translation
313 assert cancelled_exception
314 else:
315 # best we can do is check that the test ran
316 pass
317
318 # raise to main
319 with raises(ValueError):
320 res = module.surprise(thread.get_ident(), ValueError)
321 while 1:
322 print("sleeping")
323 time.sleep(0.1)
324
325 @pytest.mark.xfail('not config.option.runappdirect', reason='segfaults', run=False)
326 def test_frame_tstate_tracing(self):
327 import sys, threading
328 module = self.import_extension('foo', [
329 ("call_in_temporary_c_thread", "METH_O",
330 """
331 PyObject *res = NULL;
332 test_c_thread_t test_c_thread;
333 long thread;
334
335 PyEval_InitThreads();
336
337 test_c_thread.start_event = PyThread_allocate_lock();
338 test_c_thread.exit_event = PyThread_allocate_lock();
339 test_c_thread.callback = NULL;
340 if (!test_c_thread.start_event || !test_c_thread.exit_event) {
341 PyErr_SetString(PyExc_RuntimeError, "could not allocate lock");
342 goto exit;
343 }
344
345 Py_INCREF(args);
346 test_c_thread.callback = args;
347
348 PyThread_acquire_lock(test_c_thread.start_event, 1);
349 PyThread_acquire_lock(test_c_thread.exit_event, 1);
350
351 thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread);
352 if (thread == -1) {
353 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
354 PyThread_release_lock(test_c_thread.start_event);
355 PyThread_release_lock(test_c_thread.exit_event);
356 goto exit;
357 }
358
359 PyThread_acquire_lock(test_c_thread.start_event, 1);
360 PyThread_release_lock(test_c_thread.start_event);
361
362 Py_BEGIN_ALLOW_THREADS
363 PyThread_acquire_lock(test_c_thread.exit_event, 1);
364 PyThread_release_lock(test_c_thread.exit_event);
365 Py_END_ALLOW_THREADS
366
367 Py_INCREF(Py_None);
368 res = Py_None;
369
370 exit:
371 Py_CLEAR(test_c_thread.callback);
372 if (test_c_thread.start_event)
373 PyThread_free_lock(test_c_thread.start_event);
374 if (test_c_thread.exit_event)
375 PyThread_free_lock(test_c_thread.exit_event);
376 return res;
377 """), ], prologue = """
378 #include "pythread.h"
379 typedef struct {
380 PyThread_type_lock start_event;
381 PyThread_type_lock exit_event;
382 PyObject *callback;
383 } test_c_thread_t;
384
385 static void
386 temporary_c_thread(void *data)
387 {
388 test_c_thread_t *test_c_thread = data;
389 PyGILState_STATE state;
390 PyObject *res;
391
392 PyThread_release_lock(test_c_thread->start_event);
393
394 /* Allocate a Python thread state for this thread */
395 state = PyGILState_Ensure();
396
397 res = PyObject_CallFunction(test_c_thread->callback, "", NULL);
398 Py_CLEAR(test_c_thread->callback);
399
400 if (res == NULL) {
401 PyErr_Print();
402 }
403 else {
404 Py_DECREF(res);
405 }
406
407 /* Destroy the Python thread state for this thread */
408 PyGILState_Release(state);
409
410 PyThread_release_lock(test_c_thread->exit_event);
411
412 /*PyThread_exit_thread(); NOP (on linux) and not implememnted */
413 };
414 """)
415 def noop_trace(frame, event, arg):
416 # no operation
417 return noop_trace
418
419 def generator():
420 while 1:
421 yield "genereator"
422
423 def callback():
424 if callback.gen is None:
425 callback.gen = generator()
426 return next(callback.gen)
427 callback.gen = None
428
429 old_trace = sys.gettrace()
430 sys.settrace(noop_trace)
431 try:
432 # Install a trace function
433 threading.settrace(noop_trace)
434
435 # Create a generator in a C thread which exits after the call
436 module.call_in_temporary_c_thread(callback)
437
438 # Call the generator in a different Python thread, check that the
439 # generator didn't keep a reference to the destroyed thread state
440 for test in range(3):
441 # The trace function is still called here
442 callback()
443 finally:
444 sys.settrace(old_trace)
445
446
447 class TestInterpreterState(BaseApiTest):
448 def test_interpreter_head(self, space, api):
449 state = api.PyInterpreterState_Head()
450 assert state != nullptr(PyInterpreterState.TO)
451
452 def test_interpreter_next(self, space, api):
453 state = api.PyInterpreterState_Head()
454 assert nullptr(PyInterpreterState.TO) == api.PyInterpreterState_Next(state)