Issue
I have couple of functions and their execution is not dependent each other. What I am trying to do is execute them concurrently instead of sequentially (synchronous). I have added event loop as well, but I am not able to figure out if it is working correctly or not.
This is the implementation:
File 1:
import file2
def funcA():
a, b = 1, 2
file2.main(a, b)
File2:
def main(a, b):
asyncio.get_event_loop().run_until_complete(_main(a, b))
async def _main(a, b):
out1 = await funcA(a, b)
out2 = await funcB(a, b)
out3 = await funcC(a, b)
async def funcA(a, b):
result = 1 # some processing done here
return result
async def funcB(a, b):
result = 1 # some processing done here
return result
async def funcC(a, b):
result = 1 # some processing done here
return result
I am not able to figure out if these are working concurrently or not. I am adding time.sleep(10)
in any function, executions stops there. I don't want them to run in background as I need output from those functions.
Solution
One way to do what you want would be to use asyncio.run()
in main
and then gather
in the async version of main. To simulate long processing, use asyncio.sleep()
See the following code:
import asyncio
def main(a, b):
res = asyncio.run(async_main(a, b))
print(f"in main, result is {res}")
async def funcA(a, b):
print('funcA - start')
await asyncio.sleep(3)
result = (a+b) # some processing done here
print('funcA - end')
return result
async def funcB(a, b):
print('funcB - start')
await asyncio.sleep(3)
result = (a+b)*2 # some processing done here
print('funcB - end')
return result
async def funcC(a, b):
print('funcC - start')
await asyncio.sleep(3)
result = (a+b)*3 # some processing done here
print('funcC - end')
return result
async def async_main(a, b):
print("in async_main")
res = await asyncio.gather(funcA(a, b), funcB(a, b), funcC(a, b))
print(f"in async_main, result is {res}")
return res
if __name__ == "__main__":
main(1, 2)
The result is:
in async_main
funcA - start
funcB - start
funcC - start
funcA - end
funcB - end
funcC - end
in async_main, result is [3, 6, 9]
in main, result is [3, 6, 9]
Answered By - Roy2012
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.