发布
社区首页 >问答首页 >在Pythonnet中,BeginAllowThreads在从Python调用C#对象时崩溃。

在Pythonnet中,BeginAllowThreads在从Python调用C#对象时崩溃。
EN

Stack Overflow用户
提问于 2022-06-19 11:51:24
回答 1查看 165关注 0票数 0

使用Pythonnet,我从Python脚本中对CLR对象调用一个长时间运行的方法。我希望使用BeginAllowThreads来允许其他线程获得GIL,如下所述:Pythonnet线程

但是,对BeginAllowThreads的调用使整个应用程序崩溃,出现“无线程状态”错误。调用线程是一个CLR工作线程,具有GIL,所以我认为它应该有一个线程状态。

下面是代码序列的摘要:

代码语言:javascript
代码运行次数:0
复制
// 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。我在这里错过了什么?

EN

回答 1

Stack Overflow用户

发布于 2022-06-20 14:49:30

当您从Python调用C#方法时,Python.NET调用BeginAllowThreads。您所看到的崩溃是因为您不能两次调用BeginAllowThreads

如果其他线程阻塞了等待GIL,则必须将GIL锁定在其他地方。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72676653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档