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 email@example.com.
- Readers' Choice Awards 2013
- Mars Needs Women
- Linux Kernel News - November 2013
- Sublime Text: One Editor to Rule Them All?
- RSS Feeds
- Raspberry Pi: the Perfect Home Server
- December 2013 Issue of Linux Journal: Readers' Choice
- Tech Tip: Really Simple HTTP Server with Python
- IBM Will Minimize Impact of Future Disasters
- Linux Systems Administrator
- The kernel doesn't really
1 hour 24 min ago
1 hour 55 min ago
1 hour 55 min ago
4 hours 1 sec ago
- This should be very helpful
5 hours 13 min ago
- As much as I share your point
7 hours 33 min ago
- So girls had it better ?
11 hours 5 min ago
- Reply to comment | Linux Journal
11 hours 25 min ago
- why is GNOME 3 in the fifth position at 14.1 %?
16 hours 57 min ago
- Sublime Is Brilliant!
22 hours 36 sec ago