使用Pythonnet,我从Python脚本中对CLR对象调用一个长时间运行的方法。我希望使用BeginAllowThreads来允许其他线程获得GIL,如下所述:Pythonnet线程。
但是,对BeginAllowThreads的调用使整个应用程序崩溃,出现“无线程状态”错误。调用线程是一个CLR工作线程,具有GIL,所以我认为它应该有一个线程状态。
下面是代码序列的摘要:
// In the main thread Pythonnet is initialised like this:
public void Initialise()
{
PythonEngine.Initialize();
m_outerScope = Py.CreateScope( "outerscope" )
...
m_mainThreadState = PythonEngine.BeginAllowThreads();
}
...
// A python script is run on a worker thread like this.
// pyObj is a CLR object with methods the script can call, created
// with clrobj.ToPython():
void runScript( string script, PyObject pyObj, string objName)
{
using( Py.GIL() ) {
using( PyScope scope = m_outerScope.NewScope() ) {
try {
scope.Set( objName, pyObj );
scope.Exec( script );
} catch( Exception exc ) {
...
}
}
}
}
...
// Within the Python script we have something like:
objName.SomeMethod( 'message')
...
// The callback method on the CLR object looks like:
public void SomeMethod( string msg )
{
var state = PythonEngine.BeginAllowThreads();
someLongRunningFunction( msg );
PythonEngine.EndAllowThreads( state );
}
但是在调用BeginAllowThreads时会发生非状态错误。如果没有Begin/EndAllowThread调用,代码可以正常工作,但是其他线程阻塞等待GIL。
似乎工作线程在PythonEngine中没有线程状态,但是它有GIL。我在这里错过了什么?
发布于 2022-06-20 14:49:30
当您从Python调用C#方法时,Python.NET调用BeginAllowThreads
。您所看到的崩溃是因为您不能两次调用BeginAllowThreads
。
如果其他线程阻塞了等待GIL,则必须将GIL锁定在其他地方。
https://stackoverflow.com/questions/72676653
复制相似问题