because of the project requirements, it is necessary to build a multithreaded and multi-python interpreter, that is, a python interpreter is generated in each thread to execute the python script.
after querying the data, I want to initialize python in the main thread and get the state information of the python main interpreter, then generate the python interpreter in each child thread, and exchange the state information of the child interpreter into the global interpreter state information, so that the python script can be executed.
the simple code is as follows:
in the main thread, where mainState is the global PyTheadState pointer
Py_Initialize();
PyEval_InitThread();
*mainState = PyEval_SaveThread();
in child threads
PyEval_AcquireLock();//
PyThreadState *subState = Py_NewInterpreter(); //
PyEval_ReleaseLock();
...
PyEval_AcquireThread(subState);
PyRun_SimpleString(script); // script
PyEval_ReleaseThead(subState);
The test runs normally, but in practice, you need to export the CPP class to Python and some python statements need to check the return value. I"ll make some changes to the code in the child thread
PyEval_AcquireLock();//
PyThreadState *subState = Py_NewInterpreter(); //
PyEval_ReleaseLock();
...
PyEval_AcquireThread(subState);
PyObject *subObject = PyImport_ImportModule("__main__");
//PyObject *subObject = PyImport_AddModule("__main__");
PyObject *subDict = PyModule_GetDict(mainObject);
PyRun_String(script, Py_file_input, subDict, subDict); // script
PyEval_ReleaseThead(subState);
prompts PyRun_String that something is wrong.
I call
PyObject *subObject = PyImport_ImportModule("__main__");
//PyObject *subObject = PyImport_AddModule("__main__");
PyObject *subDict = PyModule_GetDict(mainObject);
PyRun_String(script, Py_file_input, subDict, subDict); // script
but the call fails in multithreading. It can be mentioned in the Python document that Py_NewInterpreter will generate a _ _ main__ module independent of the sub-interpreter, which is as separate from the main thread as possible, so it should be possible to get the _ _ main__ module of the sub-interpreter. Did I make a mistake in using the method?