嵌入python,用线程代码

时间:2015-12-05 00:08:01

标签: c# python multithreading pymongo python.net

我通过pythonnet https://github.com/pythonnet/pythonnet

将Python嵌入到我的C#应用​​程序中

我正在产生工作线程(一次一个),产生python子解释器在隔离环境和end sub intepreter中做一些工作。一切正常,直到我使用pymongo,然后Py_EndInterpreter开始失败。

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);
}

失败

if (tstate != interp->tstate_head || tstate->next != NULL)
    Py_FatalError("Py_EndInterpreter: not the last thread");

现在我真的不知道如何处理它并使代码工作。 我正在做的非常短的版本,正在失败是

            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();

1 个答案:

答案 0 :(得分:1)

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

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

Doc说:

  

关闭()

     

断开与MongoDB的连接。

     

关闭连接池中的所有套接字,然后停止监视器   的线程