V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
cxyfreedom
V2EX  ›  Python

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

  •  
  •   cxyfreedom · 2018-08-20 12:11:46 +08:00 · 1043 次点击
    这是一个创建于 2047 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 方法进行获取锁。

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1048 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 19:16 · PVG 03:16 · LAX 12:16 · JFK 15:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.