【问题标题】:Gevent incremental process through non blocking joinall()Gevent通过非阻塞joinall()增量处理
【发布时间】:2011-11-09 10:12:25
【问题描述】:

在这里,我想为我的设置做一些修改。

我希望在向我的服务器发出的单个请求中获得多个 API 调用的响应。从所有这些 API 调用中,我想组合结果并将它们作为响应返回。到这里为止,几乎所有内容都按照 gevent 文档和这里的示例中给出。现在这里的问题是我想以增量方式传递响应,所以如果第一个 API 调用返回了结果,我将在一个等待已久的请求中将此结果返回到前端,然后等待其他 API 调用并将它们在同一个请求中传递给前端。

我曾尝试通过代码执行此操作,但我不知道如何进行此设置。 gevent .joinall().join() 阻塞,直到所有 greenlet 都完成响应。

在此设置中我可以通过什么方式继续使用 gevent ?

我在这里使用的代码在链接 https://bitbucket.org/denis/gevent/src/tip/examples/concurrent_download.py 上给出。这里最后一条语句中的.joinall() 等到所有 url 都有完整的响应,我希望它是非阻塞的,以便我可以在回调函数 print_head() 中处理响应并逐步返回它们。

#!/usr/bin/python
# Copyright (c) 2009 Denis Bilenko. See LICENSE for details.

"""Spawn multiple workers and wait for them to complete"""

urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']

import gevent
from gevent import monkey

# patches stdlib (including socket and ssl modules) to cooperate with other greenlets
monkey.patch_all()

import urllib2


def print_head(url):
    print ('Starting %s' % url)
    data = urllib2.urlopen(url).read()
    print ('%s: %s bytes: %r' % (url, len(data), data[:50]))

jobs = [gevent.spawn(print_head, url) for url in urls]

gevent.joinall(jobs)

【问题讨论】:

    标签: python urllib gevent monkeypatching


    【解决方案1】:

    如果你想从多个greenlets中收集结果,那么修改print_head()返回结果,然后使用.get()方法将它们全部收集。

    把这个放在joinall()之后:

    total_result = [x.get() for x in jobs]
    

    实际上,joinall() 在这种情况下甚至都不需要。

    如果print_head() 看起来像这样:

    def print_head(url):
        print ('Starting %s' % url)
        return urllib2.urlopen(url).read()
    

    那么total_result 将是一个大小为 3 的列表,其中包含所有请求的响应。

    【讨论】:

    • 我尝试修改 print_head() 以返回结果并为作业列表中的每个作业执行 .get() 但问题仍然存在,即 .get() 阻塞,我可以改用非阻塞的东西吗并在同一执行流程中持续监控每个作业的结果。
    • .get() 只阻塞当前的greenlet;其他作业在 get() 期间运行;还有一个“value”属性,它是 None,一旦完成,它将被设置为“print_head”的返回值。在工作完成之前,“价值”为无。
    猜你喜欢
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2012-06-11
    • 2019-11-16
    • 2014-11-20
    相关资源
    最近更新 更多