Issue
Say I have the following code in a python function:
await asyncio.gather(
task1(),
task2(),
task3()
)
Where task1
will run an infinite loop to receive messages from a ws server and task2
is a function with a finite loop that returns a boolean.
The problem is that I need to get the response of task2
in order to do task3
.
Like : if task2 returns True, do task3, else, do nothing.
How can I get the returned boolean from Task2
? If I run task2
outside the gather function (after the function), it will never run because of the infinite loop of Task1
.
And task2
need to be runned at the same time or after task1
so I can't run task2
before the gather function either.
Solution
Remember that programming asynchronous code is exactly the same as programming syncronous code, except when you explicitly use parallelism. At task level, that means calling asyncio.gather
or other function to wait for the execution of several tasks in parallel - but otherwise, your code run "as is" only been able to switch to other tasks when an await
is encountered.
If you have things that need ordered execution, just create a function spelling the order you need, awaiting where necessary to allow for parallelism of unrelated tasks.
In other words, to have task3 wait for task2 and both disregarding task1, group the tasks that have an execution order in a plain co-routine function, using await
for each task - and then pass this, parallelizable, co-routine as a task:
...
async def task_grouper():
result = await task2()
if result:
await task3()
async def main():
await asyncio.gather(
task1(),
task_grouper()
)
...
Answered By - jsbueno
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.