V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
MartinWu
0D
V2EX  ›  Python

关于 python 的线程问题

  •  
  •   MartinWu ·
    Martwu · Nov 1, 2015 · 3659 views
    This topic created in 3836 days ago, the information mentioned may be changed or developed.

    代码如图所示:

    from threading import Timer
    import time
    
    timer_i = 1
    
    def delayrun():
        print "running..."
        t = Timer(timer_i, delayrun)
        t.start()
    
    t = Timer(timer_i, delayrun)
    t.start()
    
    while True:
        time.sleep(0.1)
        print "main process..."
    

    想问的是, delayrun 这样被嵌套调用,应该是会入栈的吧,但是实际运行时,观察线程数跟内存啊, cpu 之类的都一直稳定在某个值左右。

    求解释下这里的结构。。

    3 replies    2015-11-02 10:35:10 +08:00
    xiazi
        1
    xiazi  
       Nov 2, 2015
    delayrun 并没有被嵌套调用, 只是作为 Timer 的回调, 你这段代码的作用实际相当于一个 loop:

    while 1:
    sleep(timer_i)
    print "running..."
    ryanking8215
        2
    ryanking8215  
       Nov 2, 2015
    delayrun 每次跑起定时器后就退出去了,没有嵌套
    waklin
        3
    waklin  
       Nov 2, 2015
    t.start()是异步的并不阻塞当前函数, t.start()完成后,当前线程函就结束了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   830 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 20:13 · PVG 04:13 · LAX 13:13 · JFK 16:13
    ♥ Do have faith in what you're doing.