至于我的理解,Modules/_multiprocessing/semaphore.c
实现了内部Python对象 SemLock ,用于在Python标准库中实现 multiprocessing.synchronize.SemLock
:
class SemLock(object):
def __init__(self, kind, value, maxvalue, *, ctx):
(...A lot of other code...)
sl = self._semlock = _multiprocessing.SemLock( # <-- Here.
Modules/_multiprocessing/semaphore.c
通过在C中定义 SemLockObject 并在Python中将其导出为 SemLock 来实现此内部 SemLock 对象。
这是C定义:
typedef struct {
PyObject_HEAD
SEM_HANDLE handle;
unsigned long last_tid;
int count;
int maxvalue;
int kind;
char *name; /* <--- It has 'name'. */
} SemLockObject;
稍后 SemLockObject 在Line #617中导出为 SemLock :
PyTypeObject _PyMp_SemLockType = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing.SemLock",
/* tp_basicsize */ sizeof(SemLockObject),
除了 SemLock 之外,还会导出多个_semlock_members_,包括&#39; name&#39;。见Line #608:
static PyMemberDef semlock_members[] = {
{"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
""},
{"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
""},
{"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
""},
{"name", T_STRING, offsetof(SemLockObject, name), READONLY,
""}, /* <--- Here it is. */
{NULL}
};
因此,我有理由相信我可以在运行时访问名称成员。但是,当我检查此内部 SemLock 对象的成员时,我没有看到名称成员。这是我的检验代码:
import multiprocessing as mp
import inspect
lock = mp.Semaphore(1)
members = inspect.getmembers(lock._semlock)
for (name, _) in members:
print name
结果如下:
SEM_VALUE_MAX
__class__
__delattr__
__doc__
__enter__
__exit__
__format__
__getattribute__
__hash__
__init__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__
_after_fork
_count
_get_value
_is_mine
_is_zero
_rebuild
acquire
handle <-- 'handle' is defined in 'semlock_members'
kind <-- 'kind' is defined in 'semlock_members'
maxvalue <-- 'maxvalue' is defined in 'semlock_members'
release
但名称 ??
在哪里事实上,如果我们查看multiprocessing.synchronize.SemLock.__init__
Line #76,它会测试_semlock.name
的值:
if self._semlock.name is not None:
这让我觉得底层的_semlock有&#39;名称&#39;成员,因为否则代码会引发异常,例如&#34; AttributeError:&#39; _multiprocessing.SemLock&#39;对象没有属性&#39; name&#39;&#34;。
我一定错过了某个地方。有人会帮我指出来吗?