推荐学习书目
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
liudaqi
V2EX  ›  Python

看到 flask web 教程里启动了一个 thread 任务,为什么还要加一个 return thread 呢?(应该是任务完成自动回收吧?)

  •  
  •   liudaqi · Oct 14, 2017 · 2810 views
    This topic created in 3158 days ago, the information mentioned may be changed or developed.

    这个是教程里的示范代码,最后一行有一个 return thr

    按理,这个 thread 任务完成了,应该自动回收吧? return thr 返回的作用是什么呢?我实际测试,注释掉 return thr 或者 return None 都没有问题的。

    def send_async_email(app, msg):
        with app.app_context():
            mail.send(msg)
    
    
    def send_email(to, subject, template, **kwargs):
        app = current_app._get_current_object()
        msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                      sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
        msg.body = render_template(template + '.txt', **kwargs)
        msg.html = render_template(template + '.html', **kwargs)
        thr = Thread(target=send_async_email, args=[app, msg])
        thr.start()
        return thr
    
    2 replies    2017-10-14 14:03:09 +08:00
    awanabe
        1
    awanabe  
       Oct 14, 2017   ❤️ 1
    把创建的新对象丢到上层管理是好习惯。。
    人家写的意思,可能是如果我上层逻辑想要管理线程可以监控线程的 status
    当然你不返回也没啥问题,只要保证线程能结束,但是就无法保证是否成功结束。。除非有状态记录( DB or 缓存)
    mornlight
        2
    mornlight  
       Oct 14, 2017
    不管有没有 return, thr.start() 执行后这个线程就开始跑了,函数调用完毕后就停了。return 出去应该是保证如果想获取或控制这个线程状态时能拿到线程对象。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2891 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 59ms · UTC 05:42 · PVG 13:42 · LAX 22:42 · JFK 01:42
    ♥ Do have faith in what you're doing.