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

2017-10-14 11:34:45 +08:00
 liudaqi

这个是教程里的示范代码,最后一行有一个 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
2394 次点击
所在节点    Python
2 条回复
awanabe
2017-10-14 12:06:50 +08:00
把创建的新对象丢到上层管理是好习惯。。
人家写的意思,可能是如果我上层逻辑想要管理线程可以监控线程的 status
当然你不返回也没啥问题,只要保证线程能结束,但是就无法保证是否成功结束。。除非有状态记录( DB or 缓存)
mornlight
2017-10-14 14:03:09 +08:00
不管有没有 return, thr.start() 执行后这个线程就开始跑了,函数调用完毕后就停了。return 出去应该是保证如果想获取或控制这个线程状态时能拿到线程对象。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/397545

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX