C++ Binding with Threads

Pablo Yabo pablo.yabo at gmail.com
Tue Aug 28 09:34:57 EDT 2007


I've found a workaround for me project that I'll share.
The solution is to release the interpreter lock when a function of my wapper
is called, I mean from Python a function of C++ is called so I released the
interpreter lock and take it before returning to Python.
It's important to provide Sleep functions in your C++ code. Otherwise,
multi-threading will not work at all. If most of the work is done in your
C++ code, using this workaround will solve the issue.

To make it easier I've wrote a class to create an instance at the beginning
of each wrapped function.

Here is the constructor / destructor:

PythonAutoLock::PythonAutoLock()
{
    PythonMgr *mgr = PythonMgr::instance();

    _state = PyThreadState_Get();

    PyThreadState_Swap(NULL);
    PyEval_ReleaseLock();
}

PythonAutoLock::~PythonAutoLock()
{
    PythonMgr *mgr = PythonMgr::instance();

    PyEval_AcquireLock();
    PyThreadState_Swap(_state);
}


Pablo Yabo
--
http://www.nektra.com


On 8/13/07, Pablo Yabo <pablo.yabo at gmail.com> wrote:
>
> Hello,
>
> I want to embed Python in an application and use an API of the application
> from Python.
> The application uses a library that creates several threads and I the
> users of the application will write Python scripts handling this events.
>
> The problem is that I having problems with threads. I saw that I have to
> PyEval_InitThreads and then PyThreadState_New and PyThreadState_Swap from
> the new thread but this way to solve the problem doesn't work for me because
> I need to let 2 or more threads run at the SAME time.
> The interpreter lock doesn't let them run at the same time so I'm looking
> for another solution. I saw Py_NewInterpreter and I tried to use it but it
> doesn't work if I don't keep the lock.
>
> Can anyone help me to solve this issue or tell me 'Forget it!'?
>
>
> Thanks on advance,
> Pablo Yabo
> --
> http://www.nektra.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070828/070bdf88/attachment.html>


More information about the Python-list mailing list