Python 是否可以通过ctypes方便地访问_thread.RLock的计数?

Python 是否可以通过ctypes方便地访问_thread.RLock的计数?,python,multithreading,python-3.x,ctypes,recursive-mutex,Python,Multithreading,Python 3.x,Ctypes,Recursive Mutex,通过从类继承并从基础属性公开数据,可以为线程化创建count属性。\u RLock.\u count。这一点很容易通过示例加以说明: import threading # noinspection PyProtectedMember class RLock(threading._RLock): """RLock() -> RLock instance with count property""" @property def count(self):

通过从类继承并从基础属性公开数据,可以为
线程化创建
count
属性。\u RLock.\u count
。这一点很容易通过示例加以说明:

import threading


# noinspection PyProtectedMember
class RLock(threading._RLock):
    """RLock() -> RLock instance with count property"""

    @property
    def count(self):
        """Count property showing current level of lock ownership."""
        return self._count
  • 通过
    ctypes
    获取计数,是否可以对
    \u thread.RLock
    执行相同的操作
  • 如果可能的话,与上面显示的版本相比,该代码是否有任何优势
  • 如果这样做是有利的,那么需要编写什么代码才能访问计数
  • 是否可以通过ctypes获取计数来对_thread.RLock执行相同的操作

    是的,这是可能的,如下所示:

    import ctypes, _thread
    
    class RLock(_thread.RLock):
    
        offsetof_rlock_count = 32 # on 64-bit system
    
        @property
        def count(self):
            rlock_count_b = ctypes.string_at(id(self)+self.offsetof_rlock_count, 8)
            return int.from_bytes(rlock_count_b, 'little', signed=False)
    
    rlock = RLock()
    with rlock:
        with rlock:
            print(rlock.count)
    
    收益率:

    2
    
    或更正式的版本:

    class S_rlockobject(ctypes.Structure):
    
        _fields_ = [
            ('ob_refcnt', ctypes.c_ssize_t),
            ('ob_type', ctypes.c_void_p),
            ('rlock_lock', ctypes.c_void_p),
            ('rlock_owner', ctypes.c_long),
            ('rlock_count', ctypes.c_ulong),
            ('in_weakreflist', ctypes.c_void_p),
        ]
    
    class RLock(_thread.RLock):
    
        def __init__(self):
            super().__init__()
            self._s = S_rlockobject.from_address(id(self))
    
        @property
        def count(self):
            return self._s.rlock_count
    
    如果可能的话,与上面显示的版本相比,该代码是否有任何优势? 如果这样做是有利的,那么需要编写什么代码才能访问计数


    这两种方法都使用非公共API,很难说哪个更好,但我觉得继承纯python
    RLock
    实现更简单。性能差异在这里可以忽略。

    为什么要涉及CType或子类?如果要访问
    线程化的实现细节,为什么不直接访问对象的
    \u count
    属性作为
    任何锁来访问呢?这只是一个下划线。Python中没有
    private
    protected
    访问。您不需要像在Java中那样通过一些
    klass.getDeclaredField(“\u count”).getInt(lock)
    反射API来绕过访问控制,因为根本没有任何访问控制。尽管如此,刺穿其他库的实现细节仍然是一个坏主意。@user2357112
    \u thread.RLock
    是用C实现的,并且不公开其
    count
    属性,如果需要,可能需要通过
    ctypes
    访问。子类可以为获取数据提供有序的API<代码>线程。_RLock。_count
    在Python中是可以访问的,因为它是用Python实现的,但是C中的实现不容易允许这样的选项。啊,不同的类。您将其称为
    \u thread.RLock.\u count
    ,好像实际上有一个
    \u count
    属性,这一事实令人困惑。@user2357112希望调整后的标题有助于澄清问题。感谢您的精彩回答!我更喜欢你的正式版本,因为它看起来更适合生产环境。@noctis skytower的第一个版本将展示内部细节,谢谢你的反馈。