| 1 |
# Copyright 2015 gRPC authors. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
import threading |
| 16 |
|
| 17 |
from grpc._cython import cygrpc |
| 18 |
|
| 19 |
|
| 20 |
class SimpleFuture(object): |
| 21 |
"""A simple future mechanism.""" |
| 22 |
|
| 23 |
def __init__(self, function, *args, **kwargs): |
| 24 |
|
| 25 |
def wrapped_function(): |
| 26 |
try: |
| 27 |
self._result = function(*args, **kwargs) |
| 28 |
except Exception as error: # pylint: disable=broad-except |
| 29 |
self._error = error |
| 30 |
|
| 31 |
self._result = None |
| 32 |
self._error = None |
| 33 |
self._thread = threading.Thread(target=wrapped_function) |
| 34 |
self._thread.start() |
| 35 |
|
| 36 |
def result(self): |
| 37 |
"""The resulting value of this future. |
| 38 |
|
| 39 |
Re-raises any exceptions. |
| 40 |
""" |
| 41 |
self._thread.join() |
| 42 |
if self._error: |
| 43 |
# TODO(atash): re-raise exceptions in a way that preserves tracebacks |
| 44 |
raise self._error # pylint: disable=raising-bad-type |
| 45 |
return self._result |
| 46 |
|
| 47 |
|
| 48 |
class CompletionQueuePollFuture(SimpleFuture): |
| 49 |
|
| 50 |
def __init__(self, completion_queue, deadline): |
| 51 |
super(CompletionQueuePollFuture, |
| 52 |
self).__init__(lambda: completion_queue.poll(deadline=deadline)) |