Embedding Python in Multi-Threaded C/C++ Applications
Once your C thread is no longer using the Python interpreter, you must dispose of its resources. To do this, delete your PyThreadState object. This is accomplished with the following code:
// grab the lock PyEval_AcquireLock(); // swap my thread state out of the interpreter PyThreadState_Swap(NULL); // clear out any cruft from thread state object PyThreadState_Clear(myThreadState); // delete my thread state object PyThreadState_Delete(myThreadState); // release the lock PyEval_ReleaseLock();
This thread is now effectively done using the Python API. You may safely call pthread_exit at this point to halt execution of the thread.
Once your application has finished using the Python interpreter, you can shut down Python support with the following code:
// shut down the interpreter PyEval_AcquireLock(); Py_Finalize();
Note there is no reason to release the lock, because Python has been shut down. Be certain to delete all your thread-state objects with PyThreadState_Clear and PyThreadState_Delete before calling Py_Finalize.
Python is a good choice for use as an embedded language. The interpreter provides support for both embedding and extending, which allows two-way communication between C application code and embedded Python scripts. In addition, the threading support facilitates integration with multi-threaded applications without compromising performance.
You can download example source code at ftp.linuxjournal.com/pub/lj/listings/issue73/3641.tgz. This includes an example implementation of a multi-threaded HTTP server with an embedded Python interpreter. In order to learn more about the implementation details, I recommend reading the Python C API documentation at http://www.python.org/docs/api/. In addition, I have found the Python interpreter code itself to be an invaluable reference.
Ivan Pulleyn can be reached via e-mail at firstname.lastname@example.org.
|When BirdCam Goes Mainstream||Oct 27, 2016|
|Nightfall on Linux||Oct 26, 2016|
|Daily Giveaway - Fun Prizes from Red Hat!||Oct 25, 2016|
|Installing and Running a Headless Virtualization Server||Oct 25, 2016|
|Ubuntu MATE, Not Just a Whim||Oct 21, 2016|
|Non-Linux FOSS: Screenshotting for Fun and Profit!||Oct 20, 2016|
- Nightfall on Linux
- When BirdCam Goes Mainstream
- Installing and Running a Headless Virtualization Server
- Secure Desktops with Qubes: Compartmentalization
- Daily Giveaway - Fun Prizes from Red Hat!
- Build Your Own Raspberry Pi Camera
- Ubuntu MATE, Not Just a Whim
- Returning Values from Bash Functions
- Nasdaq Selects Drupal 8
- Polishing the wegrep Wrapper Script