使用带有线程的gevent猴子修补程序使线程可以串行工作 [英] Using gevent monkey patching with threading makes thread work serially

查看:215
本文介绍了使用带有线程的gevent猴子修补程序使线程可以串行工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 gevent ,并且我正在修补所有内容.
似乎猴子修补会导致线程顺序工作.

I am using gevent and I am monkey patching everything.
It seems like the monkey patching causes the threading to work serially.

我的代码:

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(现在在上面的代码中显示)

So the thread is not working as expected.
But if I remove the monkey.patch_all() it is working fine.
The problem is that I need the monkey.patch_all() for using gevent (now shown in the code above)

我的解决方案:

我更改了

monkey.patch_all() 

monkey.patch_all(thread=False)

所以我没有修补线程.

推荐答案

当线程在gevent中被猴子修补时,它们表现为协程.这意味着您必须显式地产生控制权,才能使其他协程得以执行.

When threads are monkey patched in gevent, they behave as coroutines. This means that you have to explicitly yield control to make it possible for other coroutines to execute.

执行此操作的方法是调用已修补的阻止操作(这将自动产生)或 :

The way to do this is call a blocking operation that has been patched (this will yield automatically) or 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'

这篇关于使用带有线程的gevent猴子修补程序使线程可以串行工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆