簡體   English   中英

使用 uWSGI 的 Python3 線程

[英]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 ,如果我動sleep(3)之前, i先增量)
我嘗試了 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

*對不起我的英語不好

發生這種情況是因為在導入您的應用程序后,主進程分叉到一個工作進程中:

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

所以你打印i的線程正在主進程中運行,你的請求由工作人員處理。 分叉期間的工作人員看到i等於 1。如果您在增加i之前移動sleep進程設法在第一個增量之前分叉。

在分叉期間不會復制除主線程之外的線程,因此i不會在工作線程中增加。

你應該使用類似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

Python 線程在 uwsgi 中默認是禁用的,您可以通過添加選項--enable-threads來啟用它:

uwsgi --http :8090 --wsgi-file uwsgi_test.py --enable-threads

它適用於我的測試環境。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM