在 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 方法进行获取锁。
希望了解的大神能解释一下,谢谢