Embedding threaded Python in C

Discussion in 'Python' started by Richard, Aug 21, 2005.

  1. Richard

    Richard Guest

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

    ----------------------------------------------------------
     
    Richard, Aug 21, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Harri Pesonen

    Re: Embedding Python in multi-threaded app

    Harri Pesonen, Sep 4, 2003, in forum: Python
    Replies:
    0
    Views:
    843
    Harri Pesonen
    Sep 4, 2003
  2. Jesper Nilsson

    Embedding Python in a threaded app

    Jesper Nilsson, Nov 3, 2003, in forum: Python
    Replies:
    0
    Views:
    260
    Jesper Nilsson
    Nov 3, 2003
  3. Mustafa Demirhan
    Replies:
    0
    Views:
    304
    Mustafa Demirhan
    Nov 9, 2004
  4. Mustafa Demirhan
    Replies:
    0
    Views:
    281
    Mustafa Demirhan
    Nov 9, 2004
  5. Mustafa Demirhan
    Replies:
    0
    Views:
    608
    Mustafa Demirhan
    Nov 9, 2004
Loading...

Share This Page