Linux/Unix > Python Essential Reference, Second Edition > B. Extending and Embedding Python > Threads | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161104058145062058222054053

### Threads

When using threads, a global interpreter lock is used to prevent more than one thread from executing in the interpreter at once. If a function written in an extension module executes for a long time, it will block the execution of other threads until it completes. This is because the lock is held whenever an extension function is invoked. If the extension module is thread-safe, the following macros can be used to release and reacquire the global interpreter lock:

    Py_BEGIN_ALLOW_THREADS

Releases the global interpreter lock and allows other threads to run in the interpreter. The C extension must not invoke any functions in the Python C API while the lock is released.

    Py_END_ALLOW_THREADS

Reacquires the global interpreter lock. The extension will block until the lock can be acquired successfully in this case.

The following example illustrates the use of these macros:

    PyObject *spamfunction(PyObject *self, PyObject *args) {
             ...
             PyArg_ParseTuple(args, ...)
             Py_BEGIN_ALLOW_THREADS
             result = run_long_calculation(args);
             Py_END_ALLOW_THREADS
             ...
             return Py_BuildValue(fmt,result);
    }

Many more subtle aspects of threads are not covered here. Readers are strongly advised to consult the C API Reference Manual. In addition, you may need to take steps to make sure that your C extension is thread-safe, as it could be invoked by other Python threads shortly after the interpreter lock is released.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.