我通过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();
看起来pymongo创建了自己的线程(用于连接池),在这种情况下,更难控制解释器的状态并优雅地关闭它。另一方面,尝试在脚本本身中执行此操作:
Doc表示:
相关问题 更多 >
编程相关推荐