GEVENT:如何等待绿色的绿色



我在几个任务生产者之间共享了一个gevent.pool(固定大小)。如果有免费插槽,每个任务生产商都可以在池中应用新的绿色。将任务添加到池中后,任务生产者应等到所有添加的任务完成。

我尝试使用gevent.queue.joinablequeue等待所有任务完成。它起作用了,除了我在等待结束时得到一个非常烦人的例外。

如何修复下面的代码以避免这种情况?也许我做错了什么?

from gevent import monkey, sleep; monkey.patch_all()
from gevent.queue import JoinableQueue
from gevent.pool import Pool
pool = Pool(3)

def worker(n):
    print 'Worker {} started'.format(n)
    sleep(1)
    print 'Worker {} finished'.format(n)
    return n

def main():
    results = []
    queue = JoinableQueue()
    for job_no in range(5):
        pool.wait_available()
        greenlet = pool.apply_async(worker, kwds=dict(n=job_no), callback=lambda ret: results.append(ret))
        queue.put(greenlet)
        sleep(.05)
    print 'All workers added'
    queue.join()
    print 'All workers finished', results

if __name__ == '__main__':
    main()

输出:

Worker 0 started
Worker 1 started
Worker 2 started
Worker 0 finished
Worker 3 started
Worker 1 finished
Worker 4 started
All workers added
Worker 2 finished
Worker 3 finished
Worker 4 finished
Traceback (most recent call last):
  File "main.py", line 32, in <module>
    main()
  File "main.py", line 27, in main
    queue.join()
  File "C:Python2.7.10x64libsite-packagesgeventqueue.py", line 492, in join
    return self._cond.wait(timeout=timeout)
  File "C:Python2.7.10x64libsite-packagesgeventevent.py", line 219, in wait
    return self._wait(timeout)
  File "C:Python2.7.10x64libsite-packagesgeventevent.py", line 129, in _wait
    gotit = self._wait_core(timeout)
  File "C:Python2.7.10x64libsite-packagesgeventevent.py", line 106, in _wait_core
    result = self.hub.switch()
  File "C:Python2.7.10x64libsite-packagesgeventhub.py", line 630, in switch
    return RawGreenlet.switch(self)
gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x26c1c28 select default pending=0 ref=0>)

您会得到'此操作将永远阻塞'错误,因为没有绿色可以在队列中消耗任务,queue.join()只能阻止所有greenlet,直到所有Greenlet完成,然后升级。

这里不需要JoinableQueue,请使用gevent.joinall()等待所有绿色完成:

import gevent
def main():
    results = []
    gs = []
    for job_no in range(5):
        greenlet = ..
        gs.append(greenlet)
    gevent.joinall(gs)
    print 'All workers finished', results

相关内容

  • 没有找到相关文章

最新更新