关于 Python 中 RLock 的源码实现问题

2018-08-20 12:11:46 +08:00
 cxyfreedom

threading.py 中,默认调用的是 _CRLock, Python 也有自己实现的_PyRLock,我测试中将默认的改为了_PyRLock。

为了测试,就单独创建了一个 RLock 对象。

lock = threading.RLock()
print(lock)

RLock 中的 acquire 源码如下:

print('Start calling acquire: owner={}, count={}'.format(self._owner, self._count))
me = get_ident()
if self._owner == me:
    self._count += 1
    print('(Counter)End calling acquire: owner={}, count={}'.format(self._owner, self._count))
    return 1
 rc = self._block.acquire(blocking, timeout)
if rc:
    print('Get the lock')
    self._owner = me
    self._count = 1
print('End calling acquire: owner={}, count={}'.format(self._owner, self._count))
return rc

print 语句是我自己添加的。 执行最上面两行后,结果如下:

Start calling acquire: owner=None, count=0
Get the lock
End calling acquire: owner=140736157979584, count=1
Start calling acquire: owner=None, count=0
Get the lock
End calling acquire: owner=140736157979584, count=1
<unlocked threading._RLock object owner=None count=0 at 0x104b7b780>
Start calling acquire: owner=None, count=0
Get the lock
End calling acquire: owner=140736157979584, count=1
Start calling acquire: owner=140736157979584, count=1
(Counter)End calling acquire: owner=140736157979584, count=2
Start calling acquire: owner=None, count=0
Get the lock
End calling acquire: owner=140736157979584, count=1

不太理解为何创建对象后,结果在 <unlocked threading._RLock object owner=None count=0 at 0x104b7b780> 这句话后,还会进行计数器的变动和获取锁的过程,而且我创建的时候也没有直接调用 acquire 方法进行获取锁。

希望了解的大神能解释一下,谢谢

1088 次点击
所在节点    Python
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/481390

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX