python - 服务器关闭之前后台线程未启动

标签 python multithreading flask uwsgi

在Web应用程序中启动并运行简单的多线程功能时,我遇到了一些麻烦。

我在Ubuntu 12.04上使用Flask,uwsgi,nginx。

每次我启动新线程时,在关闭uwsgi服务器之前它都不会执行。非常奇怪!

如果我正在执行简单的任务(例如打印),它将按预期执行9/10次。如果我执行繁重的计算工作(例如,文件上的OCR),它将在服务器重新启动(执行关闭操作)时始终开始执行

知道为什么我的代码无法按预期执行吗?

代码:

def hello_world(world):
    print "Hello, " + world # This will get printed when the uwsgi server restarts

def thread_test():
    x = "World!"
    t = threading.Thread(target=hello_world, args=(x,))
    t.start()

@application.route('/api/test')
def test():
    thread_test()
    return "Hello, World!", 200

编辑1:

我的uwsgi配置看起来像这样:
[uwsgi]
chdir       = /Users/vingtoft/Documents/Development/archii/server/archii2/
pythonpath  = /Users/vingtoft/Documents/Development/archii/server/archii2/
pythonpath  = /Users/vingtoft/Documents/Development/archii/server/ml/
module      = app.app:application
master      = True
vacuum      = True
socket      = /tmp/archii.sock 
processes   = 4
pidfile     = /Users/vingtoft/Documents/Development/archii/server/archii2/uwsgi.pid 
daemonize   = /Users/vingtoft/Documents/Development/archii/server/archii2/uwsgi.log
virtualenv  = /Users/vingtoft/Documents/Development/virtualenv/flask/
wsgi-file   = /Users/vingtoft/Documents/Development/archii/server/archii2/app/app.py
ssl         = True

最佳答案

默认情况下,uWSGI服务器将禁用线程支持以提高性能,但是您可以使用以下任一方法将其启用:

threads = 2 # or any greater number

或者
enable-threads = true

但是被警告,第一个方法将告诉uWSGI为您的每个 worker 创建2个线程,因此对于4个 worker ,您将最终得到8个实际线程。

该线程将作为单独的工作线程工作,因此它们不供您用于后台作业,但是使用大于一个的任意数量的线程将为uWSGI服务器启用线程支持,因此现在您可以为某些后台任务创建更多线程。

关于python - 服务器关闭之前后台线程未启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35140860/

相关文章:

python - Odoo 8 从向导打开 TreeView

python - 实现 Python `when` 构造的最佳方法是什么?

python - 如何在 Fabric 2 中使用 Connection?

python - Dreamhost 上的 Flask Passenger WSGI

python - 如何为数组验证提供多个选项?

java - 按程序生成一个巨大的宇宙

java - 停止后台执行的线程,然后返回结果

c - CtrlEvents的处理程序如何在多线程环境中工作?

python - Flask RestPlus 继承模型无法按预期工作

Python Sqlalchemy - 如何将数据库查询的类对象结果 jsonify