For Python 3.4+, I can use asyncio
to dispatch independent tasks.
Now, I have two long running independent functions. Both functions return result, so how do I collect the two results into a single object, using asyncio
to put these two functions inside a IO loop.
import asyncio
async def long_func1():
await ...
...
async def long_func2():
await ...
...
If I'm getting what you are trying to do...
In order to run both of the function at the same time you can use the asyncio.create_task and asyncio.wait for the results of them.
Have a look at the following example:
import sys
import asyncio
async def test_1():
return sys._getframe().f_code.co_name
async def test_2():
return sys._getframe().f_code.co_name
async def main():
t1 = asyncio.create_task(test_1())
t2 = asyncio.create_task(test_2())
done, pending = await asyncio.wait([t1, t2])
results = [d.result() for d in done]
# The order of the finished function is unknown
print(results)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
It will run two function and will wait for both of them to finish.
Once they are done
it will gather the results of both of the done
function to the results
list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.