On Jun 15, 2012, at 11:09 PM, Roberto De Ioris wrote:
> Hi, it "looks" it work because thread can be started even without managing
> the GIL, but as soon as you need to come back to uWSGI, thread will never
> get again the GIL. Try daemonizing the threads (no-join) and you will see
> how they will stop running after the end of the WSGI callable


Ah, I see what you mean. With "--enable-threads", user-created threads are 
allowed to run *always*. Without it, user-created threads are only allowed to 
run during requests.

This can be seen with the following example:

my_thread_obj = None
a = 0

def my_thread():
    global a
    while True:
        a += 1
        time.sleep(0.1)

class application(object):

    def __init__(self, environ, start_response):
        start_response('200 OK', [])

    def __iter__(self):
        global my_thread_obj
        if not my_thread_obj:
            my_thread_obj = threading.Thread(target=my_thread)
            my_thread_obj.start()
        yield str(a) + "\n"
        time.sleep(1)
        yield str(a) + "\n"

$ uwsgi --plugins=python,http --http-socket :9999 --file path/to/app.py

$ curl http://localhost:9999/ ; sleep 10 ; curl http://localhost:9999/
Staring thread
1
10
10
20

When I add --enable-threads, instead I get:

$ curl http://localhost:9999/ ; sleep 10 ; curl http://localhost:9999/
Staring thread
1
10
110
120


I've been trying to understand the implementation here, but I'm not all that 
clear on the nitty gritty details of the Python C API for threads. I think 
what's going on is that if threads are disabled (i.e. without --enable-threads 
or --threads), uWSGI does not initialize the GIL. Threads can be created from 
within Python and this will cause the GIL to be initialized, but when control 
returns from Python to uWSGI, uWSGI doesn't let go of the GIL (because it 
doesn't know it exists), so the threads don't run. When uWSGI gets another 
request and calls back into Python, the GIL will be acquired and released as 
normal, allowing threads to run again for the duration of the request.

Is this correct?

Thanks
Duncan

_______________________________________________
uWSGI mailing list
[email protected]
http://lists.unbit.it/cgi-bin/mailman/listinfo/uwsgi

Reply via email to