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
MartinWu
V2EX  ›  Python

关于 python 的线程问题

  •  
  •   MartinWu ·
    Martwu · 2015-11-01 23:08:24 +08:00 · 2725 次点击
    这是一个创建于 3100 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如图所示:

    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 条回复    2015-11-02 10:35:10 +08:00
    xiazi
        1
    xiazi  
       2015-11-02 02:30:47 +08:00
    delayrun 并没有被嵌套调用, 只是作为 Timer 的回调, 你这段代码的作用实际相当于一个 loop:

    while 1:
    sleep(timer_i)
    print "running..."
    ryanking8215
        2
    ryanking8215  
       2015-11-02 08:52:23 +08:00
    delayrun 每次跑起定时器后就退出去了,没有嵌套
    waklin
        3
    waklin  
       2015-11-02 10:35:10 +08:00
    t.start()是异步的并不阻塞当前函数, t.start()完成后,当前线程函就结束了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   878 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 21:39 · PVG 05:39 · LAX 14:39 · JFK 17:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.