Issue
So I understand that using async ... await
python can prevent blocking and accomplish xyz to follow. But what about the opposite, where I want python to block xyz until an process has completed?
For example, suppose I have three functions, A,B & C where A should not block B and vice versa. But C should be blocked by both A and B?
async def A():
# some code
async def B():
# some code
def C():
# some code
async def handler():
# A and B not to block each other
await A()
await B()
# Must complete before C
C()
As I understand it, asyncio will implicitly infer that C should be blocked by A and B if C is defined in terms of them (or their outputs.)
But in the event that C is not defined in terms of A & B, how can it be ensured that C will only commence when A and B are complete?
Solution
If I understand you correctly, you want to run A, B in parallel and if they both finish, call C()
. You can create tasks from A()
, B()
, use asyncio.gather()
to wait for them to finish and then call C()
:
import asyncio
async def A():
await asyncio.sleep(1)
print("A finished")
async def B():
await asyncio.sleep(2)
print("B finished")
def C():
print("In C!")
async def handler():
# A and B not to block each other
tasks = {asyncio.create_task(A()), asyncio.create_task(B())}
await asyncio.gather(*tasks)
# Must complete before C
C()
asyncio.run(handler())
Prints (and finishes in 2 seconds):
A finished
B finished
In C!
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.