python - How to start coroutines and continue with synchronous tasks? -


i trying understand asyncio , port undestanding of threading. take example of 2 threads running indefinitely , non-threaded loop (all of them outputting console).

the 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') 

i tried port asyncio based on documentation.

problem 1: not understand how add non-threaded task examples saw show ongoing loop @ end of program governs asyncio threads.

i wanted have @ least 2 first threads (a , b) running in parallel (and, worst case, add third c thread well, abandonning idea of mixed thread , non-threded 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: output sequence of a, suggering b() coroutine not called @ all. isn't await supposed start a() , come execution (and start b())?

await stops execution @ point, await a(), , have infinite loop in a(), it's logical b() doesn't called. think if insert a() in mainloop().

consider example:

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

to achieve want need create future manage multiple coroutines. asyncio.gather that.

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() 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -