-
-
Notifications
You must be signed in to change notification settings - Fork 32k
bpo-32309: Implement asyncio.to_thread() #20143
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
miss-islington
merged 9 commits into
python:master
from
aeros:bpo32309-asyncio-to_thread
May 19, 2020
Merged
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d6073d5
Implement asyncio.to_thread()
aeros 72da7bd
📜🤖 Added by blurb_it.
blurb-it[bot] 520d029
Fix whitespace in threads.py
aeros 542e917
Document *args and **kwargs behavior
aeros b5b6295
Fix formatting error
aeros c44451d
Fix reST note
aeros 41af75f
Add to_thread() to high-level API index
aeros 0578704
Improve documentation examples for to_thread()
aeros be50241
Fix doctest warning
aeros File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
"""High-level support for working with threads in asyncio""" | ||
|
||
import functools | ||
|
||
from . import events | ||
|
||
|
||
__all__ = "to_thread", | ||
|
||
|
||
async def to_thread(func, /, *args, **kwargs): | ||
"""Asynchronously run function *func* in a separate thread. | ||
|
||
Return an asyncio.Future which represents the eventual result of *func*. | ||
""" | ||
loop = events.get_running_loop() | ||
func_call = functools.partial(func, *args, **kwargs) | ||
aeros marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return await loop.run_in_executor(None, func_call) | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
"""Tests for asyncio/threads.py""" | ||
|
||
import asyncio | ||
import unittest | ||
|
||
from unittest import mock | ||
from test.test_asyncio import utils as test_utils | ||
|
||
|
||
def tearDownModule(): | ||
asyncio.set_event_loop_policy(None) | ||
|
||
|
||
class ToThreadTests(test_utils.TestCase): | ||
def setUp(self): | ||
super().setUp() | ||
self.loop = asyncio.new_event_loop() | ||
asyncio.set_event_loop(self.loop) | ||
|
||
def tearDown(self): | ||
self.loop.run_until_complete( | ||
self.loop.shutdown_default_executor()) | ||
self.loop.close() | ||
asyncio.set_event_loop(None) | ||
self.loop = None | ||
super().tearDown() | ||
|
||
def test_to_thread(self): | ||
async def main(): | ||
return await asyncio.to_thread(sum, [40, 2]) | ||
|
||
result = self.loop.run_until_complete(main()) | ||
self.assertEqual(result, 42) | ||
|
||
def test_to_thread_exception(self): | ||
def raise_runtime(): | ||
raise RuntimeError("test") | ||
|
||
async def main(): | ||
await asyncio.to_thread(raise_runtime) | ||
|
||
with self.assertRaisesRegex(RuntimeError, "test"): | ||
self.loop.run_until_complete(main()) | ||
|
||
def test_to_thread_once(self): | ||
func = mock.Mock() | ||
|
||
async def main(): | ||
await asyncio.to_thread(func) | ||
|
||
self.loop.run_until_complete(main()) | ||
func.assert_called_once() | ||
|
||
def test_to_thread_concurrent(self): | ||
func = mock.Mock() | ||
|
||
async def main(): | ||
futs = [] | ||
for _ in range(10): | ||
fut = asyncio.to_thread(func) | ||
futs.append(fut) | ||
await asyncio.gather(*futs) | ||
|
||
self.loop.run_until_complete(main()) | ||
self.assertEqual(func.call_count, 10) | ||
|
||
def test_to_thread_args_kwargs(self): | ||
# Unlike run_in_executor(), to_thread() should directly accept kwargs. | ||
func = mock.Mock() | ||
|
||
async def main(): | ||
await asyncio.to_thread(func, 'test', something=True) | ||
|
||
self.loop.run_until_complete(main()) | ||
func.assert_called_once_with('test', something=True) | ||
|
||
|
||
if __name__ == "__main__": | ||
unittest.main() |
4 changes: 4 additions & 0 deletions
4
Misc/NEWS.d/next/Library/2020-05-17-02-03-09.bpo-32309.KM9psl.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
Added a new :term:`coroutine` :func:`asyncio.to_thread`. It is mainly used for | ||
running IO-bound functions in a separate thread to avoid blocking the event | ||
loop, and essentially works as a high-level version of | ||
:meth:`~asyncio.loop.run_in_executor` that can directly take keyword arguments. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.