Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Embedding threaded Python in C

Reply
Thread Tools

Embedding threaded Python in C

 
 
Richard
Guest
Posts: n/a
 
      08-21-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()

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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Embedding Python in a multi-threaded C++ application Mustafa Demirhan Python 0 11-09-2004 10:08 PM
Embedding Python in a multi-threaded C++ application Mustafa Demirhan Python 0 11-09-2004 07:06 PM
Embedding Python in a multi-threaded C++ application Mustafa Demirhan Python 0 11-09-2004 06:49 PM
Embedding Python in a threaded app Jesper Nilsson Python 0 11-03-2003 04:56 PM
Re: Embedding Python in multi-threaded app Harri Pesonen Python 0 09-04-2003 01:11 PM



Advertisments