Search code examples
pythonflaskgevent

Comparing results of Gevent threads


I am running a flask app asynchronously with gevent. My main app has:

def multiple():
    ..........
    threads = [gevent.spawn(fetch, data for i in range(2)]
    result = gevent.joinall(threads)
    print [thread.value for thread in threads]

return "DICTIONARY GOES HERE"

This runs with slightly different data which yields (from the fetch function):

 {u': False, 'delete_at': 1438759341.674, 'id': 43, 'fa': 5.4, 'created_at': 1438701741.674 }
 {u': True, 'delete_at': 1438759341.675, 'id': 44, 'fa': 9.3, 'created_at': 1438701741.675 }
 {u': False, 'delete_at': 1438759341.675, 'id': 47, 'fa': 4.7, 'created_at': 1438701741.675 }

I want to return only a dictionary with u =True, or the first one that's true if there is more than one. How can I do this?


Solution

  • I would simply write something like this:

    ...
    result = gevent.joinall(threads)
    for x in (t.value for t in threads):
        if x.u:
            return x
    

    or:

    ...
    result = gevent.joinall(threads)
    return (t.value for t in threads if t.u).next()