When using python multithreading, you need to pay attention to a lot of things. In fact, you only need to master these technical segments to ensure the integrity of this application. Next, let's take a look at how to perform the operation.
Today, I read about how to securely call multiple threads in python in multithreading applications in the last day. At the beginning, I thought it was a big fight, the Global Interpreter Lock and Thread State of the python language were a little dizzy. Later, I went through various articles and help documents for mutual reference, we found that for versions 2.4/2.5, we provided PyGILState_Ensure and PyGILState_Release.
1. Define an encapsulation class to ensure pair use of PyGILState_Ensure and PyGILState_Release, which can be nested.
- #include <python.h>
- class PyThreadStateLock
- {
- public:
- PyThreadStateLock(void)
- {
- state = PyGILState_Ensure( );
- }
- ~PyThreadStateLock(void)
- {
- PyGILState_Release( state );
- }
- private:
- PyGILState_STATE state;
- };
2. In the main thread, this process
// Initialization
Py_Initialize ();
// Initialization thread support
PyEval_InitThreads ();
// Run the command before starting the child thread. To release the global lock obtained by PyEval_InitThreads, the Child thread may not be able to obtain the global lock.
PyEval_ReleaseThread (PyThreadState_Get ());
// Other processes, such as promoter threads
......
// Ensure that all sub-thread calls are completed
PyGILState_Ensure ();
Py_Finalize ();
// You cannot call any python API later
The above is a detailed introduction to python multithreading. Hope to help you.