Gevent 取第一个结果完成

Gevent take first result to complete

我目前有一些代码可以向主要数据库集发出请求。每个请求可能需要超过超时时间。我想阅读第一个完成的结果并决定是否等待第二个。 代码看起来像这样:

GREENLET_TIMEOUT = 1  # Seconds
greenlet_a = gevent.spawn(start_request, redis_a)
greenlet_b = gevent.spawn(start_request, redis_b)
gevent.joinall([greenlet_a, greenlet_b], timeout=GREENLET_TIMEOUT)

result_a = greenlet_a.value
result_b = greenlet_b.value

我看到了类似的 post here 我试着按照这里的建议去做:

import time
import gevent
from gevent.event import Event

def first():
  time.sleep(1)
  return

def second():
  time.sleep(5)
  return

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

def callback(value):
    event.set()

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

start_time = time.time()
res = event.wait()
print("--- %s seconds ---" % (time.time() - start_time))
print(res)

我预计它会花费 1 秒多一点的时间 return 但显然它正在等待两者完成。

我还尝试了另一种使用 AsyncResult 的方法

import time
import gevent
from gevent.event import AsyncResult

result = AsyncResult()

def first():
  result.set(1)

def second():
  time.sleep(5)
  result.set(2)

first_event = gevent.spawn(first)
second_event = gevent.spawn(second)

res = result.get()
print(res)

如有任何帮助,我们将不胜感激!

我错过了猴子补丁部分。这按预期工作!

import time
import gevent
from gevent.event import AsyncResult
from gevent import monkey
monkey.patch_all(subprocess=True)

result = AsyncResult()

def first():
  result.set(1)

def second():
  time.sleep(5)
  result.set(2)

first_event = gevent.spawn(first)
second_event = gevent.spawn(second)

res = result.get()
print(res)