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?
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.
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
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.