-
Notifications
You must be signed in to change notification settings - Fork 1k
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
Move AsyncioExecutor to separate file. #6192
Merged
verult
merged 6 commits into
quantumlib:master
from
verult:stream-client/asyncio-executor-loop
Jul 26, 2023
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ffcbeb4
Move AsyncioExecutor to separate file.
verult 81a15db
Add type annotations
verult f896f38
Import ParamSpec from typing_extensions since it is not available in …
verult e3039cc
Make _instance an Optional
verult d5740fc
Fixed import order
verult 5f8a90a
Merge branch 'master' into stream-client/asyncio-executor-loop
verult 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 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,69 @@ | ||
# Copyright 2023 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from typing import Awaitable, Callable, TypeVar | ||
from typing_extensions import ParamSpec | ||
import threading | ||
|
||
import asyncio | ||
import duet | ||
|
||
|
||
R = TypeVar('R') | ||
P = ParamSpec("P") | ||
|
||
|
||
class AsyncioExecutor: | ||
"""Runs asyncio coroutines in a thread, exposes the results as duet futures. | ||
|
||
This lets us bridge between an asyncio event loop (which is what async grpc | ||
code uses) and duet (which is what cirq uses for asynchrony). | ||
""" | ||
|
||
def __init__(self) -> None: | ||
loop_future: duet.AwaitableFuture[asyncio.AbstractEventLoop] = duet.AwaitableFuture() | ||
thread = threading.Thread(target=asyncio.run, args=(self._main(loop_future),), daemon=True) | ||
thread.start() | ||
self.loop = loop_future.result() | ||
|
||
@staticmethod | ||
async def _main(loop_future: duet.AwaitableFuture) -> None: | ||
loop = asyncio.get_running_loop() | ||
loop_future.set_result(loop) | ||
while True: | ||
await asyncio.sleep(1) | ||
|
||
def submit( | ||
self, func: Callable[P, Awaitable[R]], *args: P.args, **kwargs: P.kwargs | ||
) -> duet.AwaitableFuture[R]: | ||
"""Dispatch the given function to be run in an asyncio coroutine. | ||
|
||
Args: | ||
func: asyncio function which will be run in a separate thread. | ||
Will be called with *args and **kw and should return an asyncio | ||
awaitable. | ||
*args: Positional args to pass to func. | ||
**kwargs: Keyword args to pass to func. | ||
""" | ||
future = asyncio.run_coroutine_threadsafe(func(*args, **kwargs), self.loop) | ||
return duet.AwaitableFuture.wrap(future) | ||
|
||
_instance: 'AsyncioExecutor' = None | ||
|
||
@classmethod | ||
def instance(cls) -> 'AsyncioExecutor': | ||
"""Returns a singleton AsyncioExecutor shared globally.""" | ||
if cls._instance is None: | ||
cls._instance = cls() | ||
return cls._instance |
This file contains 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: should be
Optional['AsyncioExecutor']