embedding: forcing an interpreter to end

2004-12-19 Thread pdectm
I'm trying to prototype an application which runs multiple python
scripts, each in its own interpreter and OS thread.  I've not been able
to forceable stop a script which does not respond to a request to stop.

My thought was to simply call:

PyThreadState_Clear(xxx);
PyThreadState_Delete(xxx);  // Fatal Python error: no last thread
Py_EndInterpreter(xxx);

But, this doesn't work.  The call to delete causes a fatal error.  If I
skip the call to delete, the call to EndInterpreter() ends but seg
faults abound afterwards.  A small sample follows.

I've googled my heart out and reread the threading API countless times.
Any suggest or hints would be greatly appreciated.


#include "Python.h"

#include 
#include 
#include 

PyThreadState *gtstate;

void * mythread( void *none )
{
PyEval_AcquireLock();
gtstate = Py_NewInterpreter();

PyRun_SimpleString( "import time\nwhile 1:\n\tprint \"I won't
stop\"\n\ttime.sleep(1.0)\n" );

printf( "Interpreter was shutdown ... yeah \n" );

PyEval_ReleaseLock();
}

int main(int argc, char *argv[] )
{
pthread_t thread;
PyThreadState *tstate;

Py_Initialize();
PyEval_InitThreads();
tstate = PyEval_SaveThread();

pthread_create( &thread, (pthread_attr_t *)NULL, mythread, NULL );

sleep(3);

/* Make that pesky script die */
printf( "die ... \n" );
PyEval_AcquireLock();

PyThreadState_Clear(gtstate);
//PyThreadState_Delete(gtstate);  // Fatal Python error:
Py_EndInterpreter: not the last thread

PyThreadState_Swap(gtstate);
Py_EndInterpreter(gtstate);

PyEval_ReleaseLock();
sleep(3); // Segmentation fault
PyEval_AcquireThread(tstate);
   Py_Finalize();

   return(0);
}

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding: forcing an interpreter to end

2004-12-21 Thread pdectm
> Is there any signal handler you can use in your C program? Maybe
signling
> yourself will get the control back to the C program and then you can
kill
> the interpreter.

Well, the app is multi-threaded, so I do have a big issue getting
control back to my C program.  I just can not seem to cleanly stop the
interpreter.  The best I could do is:

void terminateInterpreter( PyInterpreterState *interp )
{
PyGILState_STATE gilstate;
PyObject *exc;
PyThreadState *tstate;

gilstate = PyGILState_Ensure();
tstate = PyThreadState_Swap(interp->tstate);

exc = PyString_FromString("Die");
PyThreadState_SetAsyncExc(interp->tstate->thread_id, exc);
Py_DECREF(exc);

PyThreadState_Swap(tstate);
PyGILState_Release(gilstate);
}

> You have a Python port to uClinux?

Nope, not yet.  That would have been my next post :-)  I thought there
would have been much more work on cross-compiling and porting Python.
I may need to reconsider if Python is appropriate; the other
possibiities are javascript or lua.

-- 
http://mail.python.org/mailman/listinfo/python-list