How to start coroutines and continue synchronous tasks?

I am trying to understand asyncio and transfer my inappropriate information from threading . I will give an example of two threads working unlimited, and a non-threaded loop (all of them are displayed on the console).

threading version

 import threading import time def a(): while True: time.sleep(1) print('a') def b(): while True: time.sleep(2) print('b') threading.Thread(target=a).start() threading.Thread(target=b).start() while True: time.sleep(3) print('c') 

Now I tried to port this to asyncio based on the documentation .

Problem 1 . I don’t understand how to add a non-threaded task, since all the examples I saw show a continuous loop at the end of the program that controls the asyncio threads.

Then I wanted at least the first two threads ( a and b ) to work in parallel (and, in the worst case, add the third c as a thread, abandoning the idea of ​​a mixed thread and unused operations):

 import asyncio import time async def a(): while True: await asyncio.sleep(1) print('a') async def b(): while True: await asyncio.sleep(2) print('b') async def mainloop(): await a() await b() loop = asyncio.get_event_loop() loop.run_until_complete(mainloop()) loop.close() 

Problem 2 The output is a sequence a , assuming that coroutine b() is not called at all. Shouldn't await start a() and go back to execution (and then run b() )?

+5
source share
1 answer

await stops execution at a point, you execute await a() , and you have an infinite loop in a() , so logical b() not called. Think of it as if you are inserting a() into mainloop() .

Consider the following example:

 async def main(): while True: await asyncio.sleep(1) print('in') print('out (never gets printed)') 

To achieve what you want, you need to create a future that will manage several coroutines. asyncio.gather for this.

 import asyncio async def a(): while True: await asyncio.sleep(1) print('a') async def b(): while True: await asyncio.sleep(2) print('b') async def main(): await asyncio.gather(a(), b()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() 
+3
source

Source: https://habr.com/ru/post/1271027/


All Articles