我正在使用 gevent我正在修补所有东西。
似乎猴子修补会导致线程连续工作。
我的代码:
import threading
from gevent import monkey; monkey.patch_all()
class ExampleThread(threading.Thread):
def run(self):
do_stuff() # takes a few minutes to finish
print 'finished working'
if __name__ == '__main__':
worker = ExampleThread()
worker.start()
print 'this should be printed before the worker finished'
所以线程没有按预期工作。
但如果我删除 monkey.patch_all()
它工作正常。
问题是我需要 monkey.patch_all()
来使用 gevent(现在显示在上面的代码中)
我的解决方案:
我改了
monkey.patch_all()
到
monkey.patch_all(thread=False)
所以我没有修补线程。
最佳答案
当线程在 gevent 中被猴子修补时,它们表现为协程。这意味着您必须显式地让出控制权才能让其他协程执行。
执行此操作的方法是调用已修补的阻塞操作(这将自动生成)或 gevent.sleep
:
#!/usr/bin/env python
from gevent import monkey, sleep
monkey.patch_all()
import threading
class ExampleThread(threading.Thread):
def run(self):
for i in xrange(10):
print 'working'
sleep()
if __name__ == '__main__':
worker = ExampleThread()
worker.start()
print 'this will be printed after the first call to sleep'
关于python - 使用带有线程的 gevent 猴子补丁使线程连续工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9192539/