为什么Python没有_multiprocessing.SemLock有' name'?

时间:2017-05-18 00:29:07

标签: python-2.7 semaphore python-multiprocessing

我的环境

了解我的问题的更多背景信息

至于我的理解,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;。

我一定错过了某个地方。有人会帮我指出来吗?

1 个答案:

答案 0 :(得分:4)

您正在使用Python 2.7,但正在查看Python 3.7源代码。请参阅2.7's semlock_members