本文介绍了等到几个小菜之一完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个从两个不同的连接接收数据的函数,在从其中一个连接获得结果后,我应该关闭两个连接.
I have two functions that receives data from two different connections, and i should close both connections after getting result from one of them.
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
blocks current greenlet until both two greenlets from lst
are ready.
gevent.joinall(lst) # wait much time
print lst[0].get(block=False) # -> 'foo'
print lst[1].get(block=False) # -> 'bar'
我要等到第一或第二个小菜准备就绪:
I want to wait until eiter first or second greenlet become ready:
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
我该怎么办?
推荐答案
您可以使用gevent.event.Event(或AsyncResult)和Greenlet的link()方法,如下所示:
You could use gevent.event.Event (or AsyncResult) and Greenlet's link() method, like this:
...
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()
...
这篇关于等到几个小菜之一完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!