gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:24:45 27 4
gpt4 key购买 nike

可以通过从类继承并公开基础属性的数据来​​为 threading._RLock._count 创建一个 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
  1. 是否可以通过 ctypes 获取计数来对 _thread.RLock 执行相同的操作?
  2. 如果可能,该代码是否比上面显示的版本有任何优势?
  3. 如果有利的话,需要编写什么代码才能访问计数?

最佳答案

Is it possible to do the same with the _thread.RLock by getting the count via ctypes?

是的,有可能,如 rlockobject strunct definition给出:

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

If it is possible, would the code have any advantages over the version shown above? If it would be advantageous, what code would one have to write to access the count?

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

关于python - 是否可以通过ctypes方便地访问_thread.RLock的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519605/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com