Why is `gevent.spawn` different than a monkeypatched `threading.Thread()`? Why is `gevent.spawn` different than a monkeypatched `threading.Thread()`? multithreading multithreading

Why is `gevent.spawn` different than a monkeypatched `threading.Thread()`?


What happen in your code is that the greenlets that you have created in you threads list didn't have yet the chance to be executed because gevent will not trigger a context switch until you do so explicitly in your code using gevent.sleep() and such or implicitly by calling a function that block e.g. semaphore.wait() or by yielding and so on ..., to see that you can insert a print before cv.wait() and see that it's called only after cv.notify_all() is called:

def wait_on_cv(x):    cv.acquire()    print 'acquired ', x    cv.wait()    ....

So an easy fix to your code will be to insert something that will trigger a context switch after you create your list of greenlets, example:

...threads = [ gevent.spawn(wait_on_cv, x) for x in range(10) ]gevent.sleep()  # Trigger a context switch...

Note: I am still new to gevent so i don't know if this is the right way to do it :)

This way all the greenlets will have the chance to be executed and each one of them will trigger a context switch when they call cv.wait() and in the mean time they willregister them self to the condition waiters so that when cv.notify_all() is called itwill notify all the greenlets.

HTH,