等到几个greenlets中的一个完成

时间:2012-11-27 07:03:52

标签: python gevent greenlets

我有两个函数从两个不同的连接接收数据,我应该在从其中一个连接获得结果后关闭这两个连接。

def first():
    gevent.sleep(randint(1, 100))  # i don't know how much time it will work
    return 'foo'

def second():
    gevent.sleep(randint(1, 100))  # i don't know how much time it will work
    return 'bar'

然后我产生了每个函数:

lst = [gevent.spawn(first), gevent.spawn(second)]

gevent.joinall阻止当前greenlet,直到来自lst的两个greenlet准备就绪。

gevent.joinall(lst)  # wait much time
print lst[0].get(block=False)   # -> 'foo'
print lst[1].get(block=False)   # -> 'bar'

我想等到第一个或第二个greenlet准备就绪:

i_want_such_function(lst)  # returns after few seconds
print lst[0].get(block=False)  # -> 'foo' because this greenlet is ready
print lst[1].get(block=False)  # -> raised Timeout because this greenlet is not ready

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您可以使用gevent.event.Event(或AsyncResult)和Greenlet的link()方法,如下所示:

...
ready = gevent.event.Event()
ready.clear()

def callback():
    ready.set()

lst = [gevent.spawn(first), gevent.spawn(second)]
for g in lst:
    g.link(callback)

ready.wait()
...