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.
|Huge Package Overhaul for Debian and Ubuntu||Jul 23, 2015|
|diff -u: What's New in Kernel Development||Jul 22, 2015|
|Shashlik - a Tasty New Android Simulator||Jul 21, 2015|
|Embed Linux in Monitoring and Control Systems||Jul 20, 2015|
|The Controversy Behind Canonical's Intellectual Property Policy||Jul 17, 2015|
|Non-Linux FOSS: Portable Apps, in the Cloud!||Jul 15, 2015|
- Huge Package Overhaul for Debian and Ubuntu
- Shashlik - a Tasty New Android Simulator
- diff -u: What's New in Kernel Development
- The Controversy Behind Canonical's Intellectual Property Policy
- Home Automation with Raspberry Pi
- Embed Linux in Monitoring and Control Systems
- Purism Librem 13 Review
- One Port to Rule Them All!
- Privacy Is Personal
- General Relativity in Python