Embedding threaded Python in C

R

Richard

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()

----------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top