在python中进行线程编程 [英] threading programming in python

查看:118
本文介绍了在python中进行线程编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在练习用烧瓶建立一个网站。现在我遇到了问题。
有一个实现注册的功能。代码如下:


$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
...
如果为真:
sendmail()
返回重定向(url_for('onepage'))

我的问题是:
当执行sendmail()时,需要很多时间。所以用户不得不等待片刻,大约4-5秒。这会带来不好的体验。我知道使用线程可以让这两个函数相互独立,但是我已经学习了很短的时间编程,所以我没有线程编程方面的经验,有没有人可以提供一些想法或代码示例来解决这个问题?

解决方案

你想要的是 线程 而不是低级别 thread 。对于这种简单的情况,不需要继承 threading.Thread ,所以你可以重写 sendmail() by

  threading.Thread(target = sendmail).start()



 导入线程


Recently I've been practicing to build a website with flask. Now i encounter a problem.
There is a function which to achieve registration. The code like this:

    def register():
        ...
        some judgment
        ...
        if true:
        sendmail()
        return redirect(url_for('onepage'))

My question is :
When preforming sendmail(), it needs much time. So the users have to wait for a moment to get "onepage", about 4-5s. This will bring a bad experience. I know that using threading can let these two functions independently of each other, but I have learnt programming for a very short time so I have no experience in threading programming, Could anybody provide some ideas or code examples for me at this problem?

解决方案

What you want is threading rather than the low-level thread. For a case this simple, there will be no need of subclassing threading.Thread, so you could just replase sendmail() by

threading.Thread(target=sendmail).start()

after an

import threading

这篇关于在python中进行线程编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆