是否可以在nogil部分使用Cython扩展类型? [英] Is it possible to use a Cython Extension Type in a nogil section?

查看:148
本文介绍了是否可以在nogil部分使用Cython扩展类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了Cython扩展类型,我想在nogil上下文中使用它。但是编译器总是抛出错误。这是我要执行的操作的一个简单示例:

I have created a Cython Extension Type and I would like to use it in a nogil context. But the compiler always throws an error. Here is a simple example of what I'm trying to do:

  1 # cython: language_level=3
  2 
  3 from cython.parallel import prange
  4 
  5 cdef class C1:
  6 
  7     cdef public:
  8         int val
  9 
 10     def __cinit__(self, value):
 11         self.val = value
 12 
 13 def iterate_C1():
 14 
 15     cdef int i
 16     cdef int N = 4
 17     cdef C1 c1_i
 18 
 19     # This compiles fine
 20     c1 = C1(4)
 21     print(f'c1.val={c1.val}')
 22 
 23     # But this doesn't
 24     with nogil:
 25         for i in prange(N):
 26             c1_i = C1(i)

我得到了很多例外,但它们都看起来像这样:

I get a number of exceptions but they all look like this:

Compiling c_one.pyx because it changed.
[1/1] Cythonizing c_one.pyx

Error compiling Cython file:
------------------------------------------------------------
...
    print(f'c1.val={c1.val}')

    # But this doesn't
    with nogil:
        for i in prange(N):
            c1_i = C1(i)
           ^
------------------------------------------------------------

c_one.pyx:26:12: Assignment of Python object not allowed without gil

Error compiling Cython file:
------------------------------------------------------------
...
    print(f'c1.val={c1.val}')

    # But this doesn't
    with nogil:
        for i in prange(N):
            c1_i = C1(i)
                    ^
------------------------------------------------------------

c_one.pyx:26:21: Calling gil-requiring function not allowed without gil

因此,在

推荐答案

您绝对不能创建 cdef 扩展类型的实例在 nogil 块中。它们最终是Python对象,需要引用计数(包括在一些非显而易见的地方,例如类型对象),Python管理的内存分配以及 ci ,包括调用其析构函数。

You definitely cannot create instances of cdef extension types inside a nogil block. They are ultimately Python objects and that requires reference counting (including in some non-obvious places, such as the type object), allocation of Python-managed memory, and deallocation of the previous contents of ci, including calling its destructor.

您应该能够访问其 cdef成员(例如 val ),并调用其标记为 nogil cdef 函数$ c>。

You should be able to access their cdef members (e.g. val for this class) and call their cdef functions that are marked as nogil.

这篇关于是否可以在nogil部分使用Cython扩展类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆