diff options
Diffstat (limited to 'Doc/library/asyncio-eventloop.rst')
-rw-r--r-- | Doc/library/asyncio-eventloop.rst | 49 |
1 files changed, 45 insertions, 4 deletions
diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst index 30996308c8..a61b971acb 100644 --- a/Doc/library/asyncio-eventloop.rst +++ b/Doc/library/asyncio-eventloop.rst @@ -749,7 +749,7 @@ Watching file descriptors invoke *callback* with the specified arguments once *fd* is available for writing. - Use :func:`functools.partial` :ref:`to pass keywords + Use :func:`functools.partial` :ref:`to pass keyword arguments <asyncio-pass-keywords>` to *func*. .. method:: loop.remove_writer(fd) @@ -963,7 +963,7 @@ Unix signals Raise :exc:`ValueError` if the signal number is invalid or uncatchable. Raise :exc:`RuntimeError` if there is a problem setting up the handler. - Use :func:`functools.partial` :ref:`to pass keywords + Use :func:`functools.partial` :ref:`to pass keyword arguments <asyncio-pass-keywords>` to *func*. .. method:: loop.remove_signal_handler(sig) @@ -990,11 +990,52 @@ Executing code in thread or process pools The *executor* argument should be an :class:`concurrent.futures.Executor` instance. The default executor is used if *executor* is ``None``. - Use :func:`functools.partial` :ref:`to pass keywords - <asyncio-pass-keywords>` to *func*. + Example:: + + import asyncio + import concurrent.futures + + def blocking_io(): + # File operations (such as logging) can block the + # event loop: run them in a thread pool. + with open('/dev/urandom', 'rb') as f: + return f.read(100) + + def cpu_bound(): + # CPU-bound operations will block the event loop: + # in general it is preferable to run them in a + # process pool. + return sum(i * i for i in range(10 ** 7)) + + async def main(): + loop = asyncio.get_running_loop() + + ## Options: + + # 1. Run in the default loop's executor: + result = await loop.run_in_executor( + None, blocking_io) + print('default thread pool', result) + + # 2. Run in a custom thread pool: + with concurrent.futures.ThreadPoolExecutor() as pool: + result = await loop.run_in_executor( + pool, blocking_io) + print('custom thread pool', result) + + # 3. Run in a custom process pool: + with concurrent.futures.ProcessPoolExecutor() as pool: + result = await loop.run_in_executor( + pool, cpu_bound) + print('custom process pool', result) + + asyncio.run(main()) This method returns a :class:`asyncio.Future` object. + Use :func:`functools.partial` :ref:`to pass keyword arguments + <asyncio-pass-keywords>` to *func*. + .. versionchanged:: 3.5.3 :meth:`loop.run_in_executor` no longer configures the ``max_workers`` of the thread pool executor it creates, instead |