Python Embedding Thread

Benjamin musiccomposition at gmail.com
Tue Jul 22 04:43:13 CEST 2008


On Jul 21, 6:56 am, o... at tuningchannel.de wrote:
> Hi :)
>
> I want to run Python in my app. That works still fine. But my app
> supports now Threads and I would like to know what to do, that it runs
> without problems.
>
> PyGILState_Release and PyGILState_Ensure should solve the problem
> right? Where do I have to put this two commands around? between each
> Command that increase, decrease a reference?

Two threads should not be running through the Python VM concurrently
in the same process. The GIL has to be held *any* time you use the
Python API. When you want to release the GIL (to process something in
C), use PY_BEGIN_ALLOW_THREADS and PY_END_ALLOW_THREADS around the
places where threads can run.
>
> Currently, this is a small code-snippet that represents the part of
> the code-execution:
>
>                                 PyObject *f_globals=NULL, *f_locals=NULL, *mod=NULL, *rv=NULL;
>
>                                 mod = PyImport_ImportModule("__main__");
>                                 if (!mod)
>                                         return;
>
>                                 f_globals = PyModule_GetDict(mod);
>                                 f_locals = PyDict_New();
>                                 PyDict_Update(f_locals, f_globals);
>                                 if (!f_locals) {
>                                                 Py_DECREF(mod);
>                                                 PyErr_Print();
>                                                 return;
>                                 }
>
>                                 rv = PyRun_String(    <my code>  , Py_file_input, f_locals,
> f_locals);
>                                 if (!rv)
>                                         PyErr_Print();
>
>                                 Py_XDECREF(rv);
>                                 Py_DECREF(mod);
>                                 Py_DECREF(f_locals);
>                                 Py_DECREF(f_locals);
>
> Thanks a lot for your help :)




More information about the Python-list mailing list