Python3 使用 uWSGI 进行线程化

Python3 threading with uWSGI

我浪费了很多时间,但找不到解决方案。
如果我在使用 uwsgi 部署的应用程序中使用线程,它们不会同步。

这里是一个简单的例子代码(wsgi.py):

from time import sleep
import threading

i = 0
def daemon():
  global i
  while True:
    i += 1
    print(i)
    sleep(3)
th = threading.Thread(target=daemon, args=())
th.start()

def application(environ, start_response):
  start_response('200 OK', [('Content-Type','text/html')])
  return [str(i).encode()]

并且当我 运行 这个应用程序时 i 在日志中增加,但是当浏览器发出请求时我总是得到 1。(或者得到 0 如果我在 i 第一个增量之前移动 sleep(3))
我尝试了 uwsgi.thread 装饰器,但得到了相同的结果。

uwsgi 配置:

[uwsgi]
socket = 127.0.0.1:3034
plugins-dir = /srv/uwsgi
plugin = python34
uid = py3utils
gid = py3utils
chdir = /srv/python/3/py3utils/tht/app/
wsgi-file = wsgi.py
enable-threads = true
daemonize = %(chdir)/../uwsgi.log
master = true
die-on-term = true
touch-reload = ../uwsgi_restart.txt

*对不起我的英语

Python线程在uwsgi中默认是禁用的,你可以通过添加选项--enable-threads:

来启用它
uwsgi --http :8090 --wsgi-file uwsgi_test.py --enable-threads

它在我的测试环境中有效。

发生这种情况是因为在导入您的应用程序后,主进程分叉到一个工作进程中:

spawned uWSGI master process (pid: 7167)
spawned uWSGI worker 1 (pid: 7169, cores: 1)
spawned uWSGI http 1 (pid: 7170)

所以你打印i的线程在master进程中是运行,你的请求由worker处理。分叉期间的工作人员看到 i 等于 1。如果在递增 i 之前移动 sleep,则进程会在第一次递增之前分叉。

除主线程外的线程在 fork 期间不会被复制,因此 i 不会在 worker 中递增。

你应该使用 uwsgidecorators.thread:

from time import sleep
import threading
import uwsgidecorators

i = 0

@uwsgidecorators.postfork
@uwsgidecorators.thread
def daemon():
  global i
  while True:
    i += 1
    print(i)
    sleep(3)

def application(environ, start_response):
  start_response('200 OK', [('Content-Type','text/html')])
  return [str(i).encode()]

或使用:

[uwsgi]
master = false