I am playing around with gevent, and I am trying to understand why my code is blocking and how I can fix it.
I have a pool of greenlets, and each of them talk to a thrift client which gathers data from a remote thrift server. For the purpose of the exercise, the thrift server always take > 1s to return any data.
When I spawn the greenlets, and run join, they don't execute all in parallel, but instead one after the other. My understanding is that this is happening because my code is "blocking", since when I run monkey.patch_all()
, all greenlets magically run in parallel.
So how do I make the code non-blocking myself rather that monkey patching everything and not understanding what it's doing?
An example here of what I don't understand :
import time
from gevent.pool import Pool
def hello():
print 'Hello %d' % time.time()
time.sleep(1)
def main():
pool = Pool(5)
for _ in xrange(5):
pool.spawn(hello)
pool.join()
if __name__ == '__main__':
main()
Output
Hello 1345477112
Hello 1345477113
Hello 1345477114
Hello 1345477115
Hello 1345477116
I know I could be using gevent.sleep, but how to make that function non blocking with the regular time.sleep?
Thanks