小编Vla*_*nov的帖子

等到几个小绿之一完成

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

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 …
Run Code Online (Sandbox Code Playgroud)

python gevent greenlets

1
推荐指数
1
解决办法
3896
查看次数

标签 统计

gevent ×1

greenlets ×1

python ×1