推荐学习书目
› 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 · Aug 27, 2017 · 2744 views
    This topic created in 3318 days ago, the information mentioned may be changed or developed.

    我有一个需求需要启动 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 replies  •  2017-08-28 00:53:06 +08:00
    NoAnyLove
        1
    NoAnyLove  
       Aug 28, 2017
    这种能看文档解决的问题就没必要写那么多文字来问了吧,浪费自己和大家的时间,

    > A **one-time** event that stores a value or an exception.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5326 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:32 · PVG 11:32 · LAX 20:32 · JFK 23:32
    ♥ Do have faith in what you're doing.