Error Scenario:
Workaround:
First, the definition of a package class, mainly to ensure pygilstate_ensure, pygilstate_release pairing use, and this class can be nested use.
#include <python.h>
Class Pythreadstatelock
{
Public
Pythreadstatelock (void)
{
State = Pygilstate_ensure ();
}
~pythreadstatelock (void)
{
Pygilstate_release (state);
}
Private
Pygilstate_state State;
};
Second, in the main thread, this processing
Initialization
Py_initialize ();
Initializing thread support
Pyeval_initthreads ();
Before the child thread is started, the child thread may not be able to obtain a global lock in order to release the global lock acquired by Pyeval_initthreads.
Pyeval_releasethread (Pythreadstate_get ());
Other processing, such as starting a child thread, etc.
......
After the child thread call is guaranteed to end
Pygilstate_ensure ();
Py_finalize ();
No more Python APIs can be invoked after that
Third, in the main thread, or sub-thread, the call Python itself functions are treated as follows
{
Class Pythreadstatelock Pythreadlock; //Get global lock
Call Python's API function to handle
......
}
Scoped end,Pythreadlock destructor, releasing global lock
Calling Python API functions in multi-threaded C + +