gevent AsyncResult 结果不一致问题

2017-08-27 21:24:42 +08:00
 SlipStupig

我有一个需求需要启动 100 个 coroutine 然后讲结果异步传输过去,我就用 AsyncResult 来接受结果,但是接受的结果却只有最后一次,代码如下:

# coding=utf8

from gevent.monkey import patch_all
patch_all()
import gevent
from gevent.event import AsyncResult
from gevent.pool import Pool
from gevent import Greenlet


async = AsyncResult()
pool = Pool()


def Recv():
    async.wait()
    print 'recv:{0}'.format(async.get())


class Send(Greenlet):

    def __init__(self, v):
        self.v = v
        self.event = async
        self.pool = pool
        super(Send, self).__init__()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.event.set_exception(ValueError)

    def _run(self):
        gevent.sleep(3)
        print 'send:{0}'.format(self.v)
        self.event.set(self.v)


def main():

    for i in xrange(10):
        s = Send(i)
        pool.start(s)
        pool.spawn(Recv)

    pool.join()


if __name__ == '__main__':
    main()

但是运行结果却是这样的:

send:0
send:1
send:2
send:3
send:4
send:5
send:6
send:7
send:8
send:9
recv:9
recv:9
recv:9
recv:9
recv:9
recv:9
recv:9
recv:9
recv:9
recv:9

怎么才能完整接收到 send 的结果而且不堵塞其它的协程呢?(顺序不重要)

1928 次点击
所在节点    Python
2 条回复
NoAnyLove
2017-08-28 00:46:05 +08:00
这种能看文档解决的问题就没必要写那么多文字来问了吧,浪费自己和大家的时间,

> A **one-time** event that stores a value or an exception.
mengskysama
2017-08-28 00:53:06 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/386190

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX