服务器关闭前后台线程未启动
Background threads not starting before server shutdown
我在我的 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为你的每个工人创建2个线程所以对于4个工人,你会最终得到 8 个实际线程。
线程将作为单独的工作线程工作,因此它们不适合您用于后台作业,但使用任何大于一个的线程数都将为 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为你的每个工人创建2个线程所以对于4个工人,你会最终得到 8 个实际线程。
线程将作为单独的工作线程工作,因此它们不适合您用于后台作业,但使用任何大于一个的线程数都将为 uWSGI 服务器启用线程支持,因此现在您可以创建更多线程一些后台任务。