0

In the Python documentation, it states:

Application developers should typically use the high-level asyncio functions, such as asyncio.run(), and should rarely need to reference the loop object or call its methods.

Consider also using the asyncio.run() function instead of using lower level functions to manually create and close an event loop.

If I need to use asyncio and a ThreadPoolExecutor, how would I submit the executor to the event loop?

Normally you could do:

   # Create a limited thread pool.
    executor = concurrent.futures.ThreadPoolExecutor(
        max_workers=3,
    )

    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(
            run_blocking_tasks(executor)
        )
    finally:
        event_loop.close()
Community
  • 1
  • 1
  • 1
    Can you kindly elaborate why do you need `ThreadPoolExecutor`? Running multiple event loops in threads won't speedup thing due to GIL. | Or maybe you want to run some blocking operation while event loop is running? In this case you should pass `ThreadPoolExecutor` into `run_in_executor` like shown [here](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor). | In case written above is confusing, consider reading [this answer](https://stackoverflow.com/a/33399896/1113207). – Mikhail Gerasimov Dec 05 '19 at 08:40
  • You can replace the last seven lines with `asyncio.run(run_blocking_task(executor))`. That is equivalent to the code you posted, but avoids manual teardown of the event loop. Does that answer your question? – user4815162342 Dec 05 '19 at 09:41
  • @MikhailGerasimov - I found that exact sample (Python docs) moments after I posted the question. It answered what I was looking for. –  Dec 05 '19 at 13:07

0 Answers0