嵌入python,用线程cod结束subintepreter

2024-09-26 22:53:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过pythonnethttps://github.com/pythonnet/pythonnet将Python嵌入到我的C应用程序中

我正在生成工作线程(一次一个),它派生python子解释器在隔离环境中执行一些工作,并结束子intepreter。一切都很好,直到我使用pymongo,在那之后Py嫒end解释器开始失效。在

Py_EndInterpreter(PyThreadState *tstate)
{
    PyInterpreterState *interp = tstate->interp;

    if (tstate != PyThreadState_GET())
        Py_FatalError("Py_EndInterpreter: thread is not current");
    if (tstate->frame != NULL)
        Py_FatalError("Py_EndInterpreter: thread still has a frame");
    if (tstate != interp->tstate_head || tstate->next != NULL)
        Py_FatalError("Py_EndInterpreter: not the last thread");

    PyImport_Cleanup();
    PyInterpreterState_Clear(interp);
    PyThreadState_Swap(NULL);
    PyInterpreterState_Delete(interp);
}

它失败了

^{pr2}$

现在我真的不知道如何处理这个问题,让代码正常工作。 我正在做的事情的简短版本,是失败

            Runtime.Py_Initialize();
            Runtime.PyEval_InitThreads();

            IntPtr thread_state = Runtime.PyEval_SaveThread();


            IntPtr gil = Runtime.PyGILState_Ensure();

            int i = 0;
            while (i < 5)
            {
                AutoResetEvent resetEvent = new AutoResetEvent(false);               
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += (o, ea) =>
                {
                    Thread.Sleep(2000);
                    IntPtr interpreter = Runtime.Py_NewInterpreter();

                    string str = @"
import pymongo
client = pymongo.MongoClient(""localhost"")";
                    Runtime.PyRun_SimpleString(str);
                    Runtime.Py_EndInterpreter(interpreter);

                    resetEvent.Set();
                };
                worker.RunWorkerAsync();
                resetEvent.WaitOne();

                i++;
            }

            Runtime.PyThreadState_Swap(thread_state);
            Runtime.PyGILState_Release(gil);

            Runtime.PyEval_RestoreThread(thread_state);
            Runtime.Py_Finalize();

Tags: pyifthreadnullruntimestatepymongointerp
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:10

看起来pymongo创建了自己的线程(用于连接池),在这种情况下,更难控制解释器的状态并优雅地关闭它。另一方面,尝试在脚本本身中执行此操作:

                    string str = @"
import pymongo
client = pymongo.MongoClient(""localhost"")
client.close()";

Doc表示:

close()

Disconnect from MongoDB.

Close all sockets in the connection pools and stop the monitor threads.

相关问题 更多 >

    热门问题