等到几个小绿之一完成

Vla*_*nov 1 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'
Run Code Online (Sandbox Code Playgroud)

然后我生成每个函数:

lst = [gevent.spawn(first), gevent.spawn(second)]
Run Code Online (Sandbox Code Playgroud)

gevent.joinall阻塞当前的 greenlet,直到两个 greenlet 都lst准备好。

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

我想等到第一个或第二个 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
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

ari*_*lou 5

您可以使用 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()
...
Run Code Online (Sandbox Code Playgroud)