Search code examples
pythonasynchronousgevent

python gevent asyncResult send different value to coroutine


It's easy to send value to different coroutine in gevent.event.AsyncResult like following code.

import gevent
from gevent.event import AsyncResult
a = AsyncResult()

def f1():
    gevent.sleep(3)
    a.set('Hello')

def f2():
    print a.get()

def f3():
    print a.get()

gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2),
    gevent.spawn(f3),
])

But i want to send different values to different coroutine/function through f1 function, for example:
1.f1 send 'hello' to f2 so f2 can get 'hello' message through a.get()
2.f1 send 'world' to f3 so f3 can get 'world' message through a.get()
Does anyone have good solutions ? Thanks verymuch!


Solution

  • Without context for what you're really trying to accomplish, I can't say whether this makes any sense, however you could try...

    Having two different async results:

    import gevent from gevent.event
    import AsyncResult
    a = AsyncResult()
    b = AsyncResult()
    
    def f1():
        gevent.sleep(3)
        a.set('Hello')
        b.set('World')
    
    def f2():
        print a.get()
    
    def f3():
        print b.get()
    
    gevent.joinall([
        gevent.spawn(f1),
        gevent.spawn(f2),
        gevent.spawn(f3), ])
    

    Or pass back multiple results in a data structure, and each function looks up the result they want:

    import gevent
    from gevent.event import AsyncResult
    a = AsyncResult()
    
    def f1():
        gevent.sleep(3)
        a.set({'first':'Hello', 'second':'World'})
    
    def f2():
        print a.get()['first']
    
    def f3():
        print a.get()['second']
    
    gevent.joinall([
        gevent.spawn(f1),
        gevent.spawn(f2),
        gevent.spawn(f3),
    ])