Reputation: 11
import threading,gevent,gevent.monkey
class test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print 1
gevent.sleep(2)
print 2
gevent.monkey.patch_thread()
t=test()
t.start()
why 'print 2' not run, how to do?
If to download files,multithread and gevent, which is faster?
Upvotes: 0
Views: 3636
Reputation: 3780
It's a valid question.
This is because in gevent, as soon as the main greenlet exits, the program exits. With threading, Python waits for all of the threads to finish.
You have two options there:
t.join()
at the end of your script. This will wait for t
to finish. You'll need to do this for all of your non-background threads.gevent.wait()
at the end of your script. This will wait for event loop to exit - which means all greenlets and threads.Note, that gevent.wait()
is only available in 1.0 (download 1.0rc here). The join
is available in all versions.
Upvotes: 2
Reputation: 6232
Why do you try to use gevent
inside thread
class inheritor?
Working example:
>>> import threading, gevent, gevent.monkey
>>> gevent.monkey.patch_thread()
>>> def run(self):
... print 1
... gevent.sleep(2)
... print 2
...
>>> gevent.joinall([gevent.spawn(run, [])])
1
2
>>>
Upvotes: 0