Let’s use our knowledge of async/await
syntax to do some complicated tasks.
If we wanted to run multiple tasks, we can do a setup that is similar to how we created multiple threads. Let’s walk through the following code:
async def main(): tasks = [task1(arg1), task2(arg2), task3(arg3)] await asyncio.gather(*tasks)
Breaking this down, we define main()
as a coroutine function. tasks
is a list of separate function calls. Note that each of task1()
, task2()
, and task3()
are each coroutine functions.
The next line is where the magic happens. asyncio.gather()
groups all of our tasks together and allows them to be run concurrently. You can read more about it here. It is given the await
syntax. Finally *tasks
unpacks the tasks
lists.
Let’s practice this in our own example!
Instructions
Inside of main_async()
below # your code goes here
, use the .gather()
asyncio method to group together the tasks in greetings
.
Inside the terminal output, type python3 script.py
and press Enter. To check your answer, click Check Work once your program finishes running.
Call your main_async()
function. Define your .event_main_loop()
as loop
. What do you think the output will be? How long do you think the execution will take?
Inside the terminal output, type python3 script.py
and press Enter. To check your answer, click Check Work once your program finishes running.
Change the following print statement:
print("says hello!")
to:
print(string + " says hello!")
Before running script.py, make a prediction about what the order of the outputs will be?
Inside the terminal, type python3 script.py
and press Enter. To check your answer, click Check Work once your program finishes running.