Notes

asyncio.run(main())

rather than:

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
finally:
    loop.close()

   1 import asyncio
   2 import concurrent.futures
   3 executor = concurrent.futures.ProcessPoolExecutor()
   4 
   5 item = ... # do something CPU-intensive against this
   6 cpu_intensive_thing = ... # some CPU-intensive function
   7 
   8 
   9 async def cpu_intensive_coroutine(item):
  10     loop = async.get_event_loop()
  11     result = await loop.run_in_executor(executor, cpu_intensive_thing(item))
  12     return result
  13 
  14 result = asyncio.run(cpu_intensive_coroutine(item))

   1 tasks = []
   2 tasks.append(asyncio.create_task(…))
   3 tasks.append(asyncio.create_task(…))
   4 # …
   5 for completed_task in asyncio.as_completed(*tasks):
   6     earliest_task_results = await completed_task
   7     # …

Helpers

SamatsWiki: ProgrammingLanguages/Python/asyncio (last edited 2020-06-28 04:16:00 by SamatJain)