V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
SlipStupig
V2EX  ›  Python

gevent AsyncResult 结果不一致问题

  •  
  •   SlipStupig · 2017-08-27 21:24:42 +08:00 · 1843 次点击
    这是一个创建于 2433 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我有一个需求需要启动 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 的结果而且不堵塞其它的协程呢?(顺序不重要)

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

    > A **one-time** event that stores a value or an exception.
    mengskysama
        2
    mengskysama  
       2017-08-28 00:53:06 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   978 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:14 · PVG 05:14 · LAX 14:14 · JFK 17:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.