2012-02-08 36 views
18

我使用gevent,我是猴子修补所有东西。
看起来像猴子修补会导致线程串行工作。使用gevent monkey线程修补线程使线程连续工作

我的代码:

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) 

所以我不修补该线程。

回答

20

当线程在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' 
+0

我已经编辑我的问题。我无法使用睡眠,因为我的工作需要几分钟时间, – yossi 2012-02-08 12:09:13

+3

@yossi如果你有一项任务需要很长时间才能完成,并且无法在某个时间点产生控制权,那么你需要真正的线程而不是协程。在这种情况下,我会说你最好不要补丁线程。 – jcollado 2012-02-08 12:18:26

+0

好吧,我做的是monkey.patch_all(thread = False) – yossi 2012-02-08 14:24:08