Differences between revisions 6 and 7
Revision 6 as of 2020-06-27 11:54:57
Size: 2797
Editor: SamatJain
Comment:
Revision 7 as of 2020-06-28 04:16:00
Size: 2943
Editor: SamatJain
Comment:
Deletions are marked like this. Additions are marked like this.
Line 19: Line 19:
 * CPU-intensive things should not be in await tasks. Put them into ThreadPoolExecutor, e.g.  * CPU-intensive things should not be in async tasks. Put them into ProcessPoolExecutor, e.g.
Line 24: Line 24:
executor = concurrent.futures.ThreadPoolExecutor() executor = concurrent.futures.ProcessPoolExecutor()
Line 38: Line 38:
 * Python 3.9 has `async.to_thread()` which is a higher level of the above but into a ThreadPoolExecutor. It's only useful for IO-bound tasks.

Notes

  • asyncio.run() gets the event loop, runs tasks until they're complete, and closes the event loop. Introduced in Python 3.7 and replaces asyncio.get_event_loop() and loop.run_until_complete(). E.g.

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))
  • Python 3.9 has async.to_thread() which is a higher level of the above but into a ThreadPoolExecutor. It's only useful for IO-bound tasks.

  • use async.create_task to turn a coroutine into a task. Tasks can be given to gather or as_comepleted

  • asyncio.gather will schedule multiple async tasks at once. Waits for all tasks to be completed, returns list of results. ( asyncio.as_completed can be looped over as tasks are completed.

   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)