Embedding threaded Python in C
Richard
richard at nospam.here
Sun Aug 21 06:33:03 EDT 2005
I've tried embedding Python in a C app so that Threading is done in the
Python side.
In the simple example below, unless I uncomment the ALLOW_THREADS macros,
the Python thread does nothing until the C for-loop finishes.
My real-world example is a large C/Motif application - apart from scattering
the ALLOW_THREADS macros everywhere (and what do you do while the Motif
event loop is idling?), is there a better way to get the Python threads to
run?
I'm using Python-2.4 on Linux.
----------------------------------------------------------
/* app.c */
#include <stdio.h>
#include <Python.h>
void run_worker(void)
{
PyObject *pmod;
PyObject *pfunc;
PyObject *pargs;
PyObject *pres;
pmod = PyImport_ImportModule("Manager");
pfunc = PyObject_GetAttrString(pmod, "run");
pargs = Py_BuildValue("()");
pres = PyEval_CallObject(pfunc, pargs);
Py_DECREF(pres);
Py_DECREF(pfunc);
Py_DECREF(pargs);
Py_DECREF(pmod);
}
int main(int argc, char **argv)
{
int i;
Py_Initialize();
PyEval_InitThreads();
PySys_SetArgv(argc, argv);
run_worker();
for (i=0; i<8; i++)
{
printf("%d main()\n", i);
/*Py_BEGIN_ALLOW_THREADS*/
sleep(1);
/*Py_END_ALLOW_THREADS*/
}
Py_Finalize();
}
----------------------------------------------------------
# Manager.py
import time
from threading import Thread, currentThread
class Worker(Thread):
def run(self):
for i in range(5):
print "Worker.run() %d [%s]" % (i, currentThread().getName())
time.sleep(1)
def run():
w = Worker()
w.start()
----------------------------------------------------------
More information about the Python-list
mailing list