Skip to content

Implement asyncio.run_in_executor shortcut #76490

Closed

Description

@asvetlov
BPO 32309
Nosy @vstinner, @asvetlov, @cjerdonek, @1st1, @miss-islington, @primal100, @aeros
PRs
  • bpo-32311: Implement asyncio.create_task() shortcut #4848
  • bpo-32309: Implement asyncio.ThreadPool #18410
  • bpo-32309: Implement asyncio.to_thread() #20143
  • [3.9] bpo-32309: Implement asyncio.to_thread() (GH-20143) #20212
  • bpo-32309: Add support for contextvars in asyncio.to_thread() #20278
  • [3.9] bpo-32309: Add support for contextvars in asyncio.to_thread() (GH-20278) #20279
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = <Date 2020-05-21.05:58:41.914>
    created_at = <Date 2017-12-13.19:54:21.835>
    labels = ['docs', '3.9', 'expert-asyncio']
    title = 'Implement asyncio.run_in_executor shortcut'
    updated_at = <Date 2020-05-21.05:58:41.913>
    user = 'https://github.com/asvetlov'

    bugs.python.org fields:

    activity = <Date 2020-05-21.05:58:41.913>
    actor = 'aeros'
    assignee = 'none'
    closed = True
    closed_date = <Date 2020-05-21.05:58:41.914>
    closer = 'aeros'
    components = ['Documentation', 'asyncio']
    creation = <Date 2017-12-13.19:54:21.835>
    creator = 'asvetlov'
    dependencies = []
    files = []
    hgrepos = []
    issue_num = 32309
    keywords = ['patch']
    message_count = 43.0
    messages = ['308238', '308239', '308243', '308245', '341352', '355771', '355773', '355796', '355798', '355799', '355800', '355802', '355804', '355805', '355807', '355809', '355811', '355842', '355846', '355852', '355854', '355855', '355857', '355858', '355862', '355863', '355881', '355883', '355938', '355957', '355975', '355978', '356242', '356303', '356776', '356792', '360725', '369318', '369331', '369408', '369493', '369495', '369497']
    nosy_count = 7.0
    nosy_names = ['vstinner', 'asvetlov', 'chris.jerdonek', 'yselivanov', 'miss-islington', 'primal', 'aeros']
    pr_nums = ['4848', '18410', '20143', '20212', '20278', '20279']
    priority = 'normal'
    resolution = 'fixed'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = None
    url = 'https://bugs.python.org/issue32309'
    versions = ['Python 3.9']

    Activity

    1. asvetlov commented on Dec 13, 2017

      @asvetlov
      ContributorAuthor

      loop.create_task() and loop.run_in_executor are present very often in user code. But they are require a loop instance, actual call looks like

      loop = asyncio.get_running_loop()
      loop.create_task(coro())

      The proposal adds create_task(coro) and run_in_executor(executor, func, *args) shortcuts for this.

    2. added
      3.7 (EOL)
      docs
      on Dec 13, 2017
    3. 1st1 commented on Dec 13, 2017

      @1st1
      Member

      I don't like the low-level API of run_in_executor. "executor" being the first argument, the inability to pass **kwargs, etc.

      I'd expect to see a more high-level API, perhaps the one that supports 'async with':

          async with asyncio.ThreadPool() as pool:
              f1 = pool.run(func1)
              f2 = pool.run(func2)
              r3 = await pool.run(func3)
      
          r1 = f1.result()
          r2 = f2.result()
          print(r1, r2, r3)

      I mean it's great that we can use 'concurrent.futures' in asyncio, but having native asyncio pools implementation would be way more convenient to the users.

      In any case, can we focus this issue on the "run_in_executor" API, and open a new one for "create_task"?

    4. asvetlov commented on Dec 13, 2017

      @asvetlov
      ContributorAuthor

      Removed create_task() from title

    5. changed the title [-]Implement asyncio.create_task() and asyncio.run_in_executor shortcuts[/-] [+]Implement asyncio.run_in_executor shortcut[/+] on Dec 13, 2017
    6. asvetlov commented on Dec 13, 2017

      @asvetlov
      ContributorAuthor
    7. asvetlov commented on May 3, 2019

      @asvetlov
      ContributorAuthor

      In Python 3.7 loop.run_in_executor() is the only user-faced method that requires a loop.

      asyncio.ThreadPool() sounds great. Maybe thread group can provide better api.

      But for Python 3.8 adding run_in_executor top-level function looks the only easy and obvious way to help people getting rid of explicit loop usage.

      Yuri, what do you think?

    8. aeros commented on Oct 31, 2019

      @aeros
      Contributor

      I don't like the low-level API of run_in_executor. "executor" being the first argument, the inability to pass **kwargs, etc.

      I mean it's great that we can use 'concurrent.futures' in asyncio, but having native asyncio pools implementation would be way more convenient to the users.

      I agree that there's an issue with this, but I think for the high level API it can be an asynchronous context manager that makes use of concurrent.futures.ThreadPoolExecutor, since that one seems to fit the majority of asyncio use cases. If users want to utilize concurrent.futures.ProcessPoolExecutor or a customized one, they can use loop.run_in_executor() instead.

      Unless there's something I'm missing with regards to concurrent.futures.ThreadPoolExecutor that specifically makes it less usable. Can't asyncio.ThreadPool make use of concurrent.futures.ThreadPoolExecutor in the internal details while providing a better API?

      I'd expect to see a more high-level API, perhaps the one that supports 'async with':

      asyncio.ThreadPool() sounds great. Maybe thread group can provide better api.

      I'd be willing to work on implementing the asyncio.ThreadPool API as Yury described it.

      But for Python 3.8 adding run_in_executor top-level function looks the only easy and obvious way to help people getting rid of explicit loop usage.

      I can see your point Andrew, but I think that if we implement asyncio.run_in_executor() and then later add asyncio.ThreadPool(), it's going to be against "one obvious way" and we'll end up adding two high-level functions for the same purpose. This principle can't always be adhered to, but I think we should try to when it's possible.

      Personally, I think the API for asyncio.ThreadPool would be much more robust, so it seems worthwhile to try implementing this one first. If there are a number of unforeseen complications, asyncio.run_in_executor() might still be a decent fallback.

    9. aeros commented on Oct 31, 2019

      @aeros
      Contributor

      end up adding two high-level functions

      Clarification: asyncio.run_in_executor() would be a function, but asyncio.ThreadPool would be a context manager class.

    10. aeros commented on Nov 1, 2019

      @aeros
      Contributor

      So, here's a prototype implementation of asyncio.ThreadPool that would function exactly as Yury described, but I'm not convinced about the design. Usually, it seems preferred to separate the context manager from the rest of the class (as was done with asyncio.Lock), but I think this one might be simple enough to be a single class:

      class ThreadPool:
          def __init__(self, timeout=None):
              self.timeout = timeout
              self._loop = None
          
          async def __aenter__(self):
              self._loop = asyncio.get_running_loop()
              # Ensure that ThreadPoolExecutor is being used
              self._loop.default_executor = concurrent.futures.ThreadPoolExecutor()
              return self
      
          async def __aexit__(self, *args):
              await self._loop.shutdown_default_executor(timeout=self.timeout)
      
          def run(self, func, *args, **kwargs):
              call = functools.partial(func, *args, **kwargs)
              return self._loop.run_in_executor(None, call)

      It utilizes the existing lower level event loop API to provide an asynchronous context manager. I'd say the main advantage is that it's significantly more user friendly, as there's no loop or executor argument to be specified, and users can freely pass kwargs to run() thanks to functools.partial().

      Additionally, I also included a timeout parameter for shutting down the ThreadPoolExecutor, which will depend upon #60564. This can be used as such:

      async def main():
          async with asyncio.ThreadPool(timeout=600) as pool:
              fut1 = pool.run(func)
              fut2 = pool.run(func, arg1, arg2)
              fut2 = pool.run(func, arg1, kwarg1=True)
          print(await asyncio.gather(fut1, fut2, fut3))
      
      asyncio.run(main())

      I don't expect that this would be the final design, but I think it's a decent prototype to demonstrate the functionality. Thoughts?

    11. asvetlov commented on Nov 1, 2019

      @asvetlov
      ContributorAuthor

      run should be awaitable method, see bpo-38430

    12. 23 remaining items

    13. 1st1 commented on Nov 8, 2019

      @1st1
      Member

      I think that I'm still not understanding something important though. Even if we initialize our ThreadPoolExecutor outside of __init__ (in a start() coroutine method, as your proposing), it seems like the threads will be spawned throughout the lifespan of the threadpool, rather than upon startup since the new threads are spawned in ThreadPoolExecutor *after* executor.submit() is called (up to max_workers) rather than upon initialization.

      Correct.

      So even if an instance of ThreadPoolExecututor is initialized asynchronously within a start() coroutine method, the individual threads within it won't be spawned at the same time.

      Correct. There are a few points of this approach:

      (a) design the API correctly;
      (b) ship something that definitely works with a proven ThreadPoolExecutor;
      (c) write lots of tests;
      (d) write docs;
      (e) if (a-d) are OK, refine the implementation later by replacing ThreadPoolExecutor with a proper (eager threads creation) implementation.

      That's why I wrote an explicit way of spawning threads in the above example, based on the way that ThreadPoolExecutor spawns threads in _adjust_thread_count(), which is called at the end of submit().

      Yeah. In your current approach you're using ThreadPoolExecutor private API, which makes the code a bit fragile. There are two alternatives:

      1. Extent ThreadPoolExecutor API to add an option of eager threads spawn.

      2. Not using ThreadPoolExecutor at all. We can write our own threads orchestration code, it's not that complicated. If we do that, our implementation will become quite faster than the current run_in_executor. We can use curio as inspiration. Last time I profiled asyncio I saw that the code binding concurrent.Future to asyncio.Future is quite complex, brittle, and slow.

      I'm in favor of (2), but let's go through (a-d) steps to get there.

    14. aeros commented on Nov 9, 2019

      @aeros
      Contributor

      (a) design the API correctly;
      (b) ship something that definitely works with a proven ThreadPoolExecutor;
      (c) write lots of tests;
      (d) write docs;
      (e) if (a-d) are OK, refine the implementation later by replacing ThreadPoolExecutor with a proper (eager threads creation) implementation.

      That sounds like a good strategy. I'll start working on step a, to build a more robust working implementation (that only uses ThreadPoolExecutor's public API), and then work on c and d once the API is approved.

      1. Not using ThreadPoolExecutor at all. We can write our own threads orchestration code, it's not that complicated. If we do that, our implementation will become quite faster than the current run_in_executor. We can use curio as inspiration. Last time I profiled asyncio I saw that the code binding concurrent.Future to asyncio.Future is quite complex, brittle, and slow.

      I'm in favor of (2), but let's go through (a-d) steps to get there.

      Agreed, I'm also in favor of option (2), but doing (a-d) first. I think this approach will provide far more stability (rather than implementing (2) immediately), as we'll be able to write extensive test coverage using a ThreadPoolExecutor implementation as a base, and then ensure the native asyncio threadpool implementation has the same intended behavior. Afterwards, could even keep the ThreadPoolExecutor version as private for testing purposes.

      The native asyncio version will likely require some additional tests to ensure that the threads are being spawned eagerly, but they should have very similar overall behavior, with the asyncio version having better performance.

      I'm thinking that we could create a new Lib/asyncio/pools.py, for the initial ThreadPoolExecutor implementation, to give us a separate area to work with for native asyncio one in the future. A similar asyncio.ProcessPool API could also be eventually created there as well. It might be feasible to fit the initial implementation in Lib/asyncio/base_events.py, but IMO the native asyncio version would not fit.

      (From the user end it would make no difference, as long as we add pools.__all__ to Lib/asyncio/init.py)

      My only remaining question that I can think of: should we implement an asyncio.ProcessPool API (using ProcessPoolExecutor's public API) before working on the native asyncio version of asyncio.ThreadPool?

      This would likely allow us to release the executor versions well before the 3.9 beta (2020-05-18), and then the native asyncio versions (with eager spawning) either before 3.9rc1 (2020-08-10) or at some point during 3.10 alpha. I suspect that writing the extensive test coverage will take the most time.

    15. aeros commented on Nov 16, 2019

      @aeros
      Contributor

      (a) design the API correctly;
      (b) ship something that definitely works with a proven ThreadPoolExecutor;

      Yury and Andrew, here's my latest API design for asyncio.ThreadPool: master...aeros:asyncio-threadpool. This is for the initial ThreadPoolExecutor version, using the design based on Yury's suggestions. I plan on extending upon the docstrings, writing tests, and the documentation for it.

      My idea was to use the new Lib/asyncio/pools.py and AbstractPool to eventually implement an asyncio.ProcessPool (and the native version of asyncio.ThreadPool).

      I plan on opening a PR after I finish writing some tests and documentation, I'd like to include it all in the same PR if possible. But let me know what you think about the current API design, it would be much easier for me to make modifications at this stage.

    16. aeros commented on Nov 17, 2019

      @aeros
      Contributor

      So, I just had an interesting idea... what if ThreadPool.run() returned a Task instead of a coroutine object?

      With the current version of asyncio.ThreadPool, if a user wants to create a Task, they would have to do something like this:

      async with asyncio.ThreadPool() as pool:
          task = asyncio.create_task(pool.run(io_blocking_func, 10, kwarg1='test'))
          other_task = asyncio.create_task(pool.run(io_blocking_func, 12))
          if some_conditional:
              task.cancel()
          results = await asyncio.gather(task, other_task, return_exceptions=True)
          ...

      To me, this looks like excessive boilerplate, particularly for a higher level API. Even for rather straightforward behavior, it requires nested function calls. If we were to return a task directly, this would be significantly cleaner:

      async with asyncio.ThreadPool() as pool:
          task = pool.run(io_blocking_func, 10, kwarg1='test')
          other_task = pool.run(io_blocking_func, 12)
          if some_conditional:
              task.cancel()
          results = await asyncio.gather(task, other_task, return_exceptions=True)
          ...

      Since asyncio.ThreadPool is intended to be a high-level API, I don't think it's an issue to return a Task from it's run() method. It would make it significantly easier and more convenient to work with from a user perspective.

      Thoughts?

    17. aeros commented on Jan 26, 2020

      @aeros
      Contributor

      So, I just had an interesting idea... what if ThreadPool.run() returned a Task instead of a coroutine object?

      After having some time to think this over, I prefer the current behavior. I don't think there would be significant enough improvement from returning a Task instead, and it would likely result in an overall performance loss.

      Also, as a general update on the project, I'm close to being ready to open a PR to implement asyncio.ThreadPool. I finished the basic implementation and added a decent number of new tests to ensure its functionality. Here's my current progress: master...aeros:asyncio-threadpool

      I just need to work on adding the new documentation, and more specifically finding a good place for it in the current asyncio docs. Do you have any ideas for that, Yury? I figured that you might already have a preference in mind.

    18. miss-islington commented on May 19, 2020

      @miss-islington
      Contributor

      New changeset cc2bbc2 by Kyle Stanley in branch 'master':
      bpo-32309: Implement asyncio.to_thread() (GH-20143)
      cc2bbc2

    19. miss-islington commented on May 19, 2020

      @miss-islington
      Contributor

      New changeset e299130 by Miss Islington (bot) in branch '3.9':
      bpo-32309: Implement asyncio.to_thread() (GH-20143)
      e299130

    20. vstinner commented on May 20, 2020

      @vstinner
      Member

      Note for myself: Python 3.9 release manager (Lukasz) approved adding the feature to Python 3.9.0 beta2:
      #20212 (review)

    21. added
      3.9 (EOL)
      and removed
      3.7 (EOL)
      on May 20, 2020
    22. miss-islington commented on May 21, 2020

      @miss-islington
      Contributor

      New changeset 0f56263 by Kyle Stanley in branch 'master':
      bpo-32309: Add support for contextvars in asyncio.to_thread() (GH-20278)
      0f56263

    23. miss-islington commented on May 21, 2020

      @miss-islington
      Contributor

      New changeset 3e65054 by Miss Islington (bot) in branch '3.9':
      bpo-32309: Add support for contextvars in asyncio.to_thread() (GH-20278)
      3e65054

    24. aeros commented on May 21, 2020

      @aeros
      Contributor

      Now that the versionadded label has been added and the contextvar issue was addressed, this issue can be closed.

    25. transferred this issue fromon Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    No one assigned

      Labels

      3.9 (EOL)docstopic-asyncio

      Projects

      No projects

        Milestone

        No milestone

        Relationships

        None yet

        Development

        No branches or pull requests

        Issue actions