Debian Codegraph @

pypy/module/cpyext/test/callback_in_thread.c

raw symbols SCIP
1 /* A test module that spawns a thread and run a function there */
2
3 #include <Python.h>
4 #include <pthread.h>
5
6 struct thread_data {
7 PyInterpreterState *interp;
8 PyObject *callback;
9 };
10
11 static void *thread_function(void* ptr) {
12 struct thread_data *data = (struct thread_data *)ptr;
13 PyInterpreterState *interp = data->interp;
14 /* Assuming you have access to an interpreter object, the typical
15 * idiom for calling into Python from a C thread is: */
16
17 PyThreadState *tstate;
18 PyObject *result;
19
20 /* interp is your reference to an interpreter object. */
21 tstate = PyThreadState_New(interp);
22 PyEval_AcquireThread(tstate);
23
24 /* Perform Python actions here. */
25 result = PyObject_CallFunction(data->callback,
26 "l", (long)pthread_self());
27 if (!result)
28 PyErr_Print();
29 else
30 Py_DECREF(result);
31
32 Py_DECREF(data->callback);
33
34 /* XXX Python examples don't mention it, but docs say that
35 * PyThreadState_Delete requires it. */
36 PyThreadState_Clear(tstate);
37
38 /* Release the thread. No Python API allowed beyond this point. */
39 PyEval_ReleaseThread(tstate);
40
41 /* You can either delete the thread state, or save it
42 until you need it the next time. */
43 PyThreadState_Delete(tstate);
44
45 free(data);
46 return NULL;
47 }
48
49 static PyObject *
50 run_callback(PyObject *self, PyObject *callback)
51 {
52 pthread_t thread;
53 struct thread_data *data = malloc(sizeof(struct thread_data));
54 Py_INCREF(callback);
55 data->interp = PyThreadState_Get()->interp;
56 data->callback = callback;
57 pthread_create(&thread, NULL, thread_function, (void*)data);
58 Py_RETURN_NONE;
59 }
60
61
62 static PyMethodDef module_functions[] = {
63 {"callInThread", (PyCFunction)run_callback, METH_O, NULL},
64 {NULL, NULL} /* Sentinel */
65 };
66
67 #ifdef __GNUC__
68 extern __attribute__((visibility("default")))
69 #else
70 extern __declspec(dllexport)
71 #endif
72
73 PyMODINIT_FUNC
74 initcallback_in_thread(void)
75 {
76 PyObject *m;
77 m = Py_InitModule("callback_in_thread", module_functions);
78 if (m == NULL)
79 return;
80 PyEval_InitThreads();
81 }
82
83 /*
84 cc -g -O0 -c callback_in_thread.c -I /usr/include/python2.6 -fPIC && ld -g -O0 callback_in_thread.o --shared -o callback_in_thread.so && gdb --args ~/python/cpython2.7/python -c "from __future__ import print_function; import threading, time; from callback_in_thread import callInThread; callInThread(print); time.sleep(1)"
85
86
87 cc -g -O0 -c callback_in_thread.c -I ~/pypy/pypy/include -fPIC && ld -g -O0 callback_in_thread.o --shared -o callback_in_thread.pypy-19.so && gdb --args ~/pypy/pypy/pypy/pypy-c -c "from __future__ import print_function; import threading, time; from callback_in_thread import callInThread; callInThread(print); time.sleep(1)"
88
89 */