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

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

  •  
  •   liudaqi · 2017-10-14 11:34:45 +08:00 · 2389 次点击
    这是一个创建于 2413 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这个是教程里的示范代码,最后一行有一个 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 条回复    2017-10-14 14:03:09 +08:00
    awanabe
        1
    awanabe  
       2017-10-14 12:06:50 +08:00   ❤️ 1
    把创建的新对象丢到上层管理是好习惯。。
    人家写的意思,可能是如果我上层逻辑想要管理线程可以监控线程的 status
    当然你不返回也没啥问题,只要保证线程能结束,但是就无法保证是否成功结束。。除非有状态记录( DB or 缓存)
    mornlight
        2
    mornlight  
       2017-10-14 14:03:09 +08:00
    不管有没有 return, thr.start() 执行后这个线程就开始跑了,函数调用完毕后就停了。return 出去应该是保证如果想获取或控制这个线程状态时能拿到线程对象。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3260 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:36 · PVG 18:36 · LAX 03:36 · JFK 06:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.