Creating a new interpreter for each thread

22 views Asked by At

My program has the following functionality: an external request is received to execute a Python script, the program creates a new interpreter in the thread and starts execution. However, for some reason, the variables set by the script in the subinterpreter allocated to it are accessible to new subinterpreters. Please tell me how can I create an isolated sub-interpreter for each CPython thread.

void RunCmd(const char* name) {
    auto main_gil_state = PyGILState_Ensure();
    auto old_thread_state = PyThreadState_Get();
    auto new_thread_state = Py_NewInterpreter();


    PyThreadState_Swap(new_thread_state);
    auto sub_thread_state = PyEval_SaveThread();
    auto sub_gil_state = PyGILState_Ensure();

    PyRun_SimpleString(name);

    PyGILState_Release(sub_gil_state);
    PyEval_RestoreThread(sub_thread_state);
    Py_EndInterpreter(new_thread_state);
    PyThreadState_Swap(old_thread_state);
    PyGILState_Release(main_gil_state);
}

int main() {
    Py_Initialize();
//  Py_DECREF(PyImport_ImportModule("threading"));
    auto main_gil_state = PyGILState_Ensure();
    auto main_thread_state = PyEval_SaveThread();

    RunCmd("MAGIC='test_str'");
    RunCmd("print(MAGIC)"); //test_str

    PyEval_RestoreThread(main_thread_state);
    PyGILState_Release(main_gil_state);
    Py_Finalize();

}
0

There are 0 answers