Python3 threading with uWSGI

Python threading is disabled by default in uwsgi, you can enable it by adding option --enable-threads:

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

It works in my test environment.


This happens because after importing your application the master process forks into a worker:

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

So your thread which prints i is running in master process, and your requests are processed by the worker. The worker during the fork sees i equal to 1. If you move sleep before incrementing i the process manages to fork before the first increment.

Threads except the main one are not copied during a fork, so i does not increment in the worker.

You should use something like 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()]

Or use:

[uwsgi]
master = false