from flask import Flask
app = Flask(__name__)
import threading
class SThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
for i in range(1, 1000):
print 0
t = SThread()
t.start()
for i in range(1, 1000):
print 1
t.join()
@app.route('/')
def hello_world():
return 'Hello, World!'
When you start your server like this, gunicorn run:app -b 0.0.0.0:8000
, you will see all 0s and 1s will be in random order, main thread and child thread are running parallel.
But when you run same piece of code with gunicorn --worker-class eventlet run:app -b 0.0.0.0:8000
, you will see first there will be all 0s and then there will be all 1s. That means main thread and child thread are not running parallel.
Is this expected behaviour?
And how can I use eventlet and make use of threading behaviour?
Edited ::
Based on suggestion, I am trying to do something like this to achieve threads like random behaviour and to join these multiple execution streams. But it is running in sequential manner only.
from flask import Flask
app = Flask(__name__)
import eventlet
def background():
for i in range(1, 10000):
print 0
return 42
def callback(gt, *args, **kwargs):
result = gt.wait()
print("[cb] %s" % result)
greenth = eventlet.spawn(background)
for i in range(1, 10000):
print 1
greenth.link(callback)
@app.route('/')
def hello_world():
return 'Hello, World!'