Skip to content

Instantly share code, notes, and snippets.

@silkentrance
Last active April 9, 2017 22:40
Show Gist options
  • Save silkentrance/afa4b52b6fc4cf37ba92d6ba0168deb0 to your computer and use it in GitHub Desktop.
Save silkentrance/afa4b52b6fc4cf37ba92d6ba0168deb0 to your computer and use it in GitHub Desktop.
GRPC Python Request and Response Streaming
import threading
from time import sleep
DEFAULT_SLEEP_TIME = 0.00001
class SyncStream:
def __init__(self, sleep_time = DEFAULT_SLEEP_TIME):
self._semaphore = threading.Semaphore()
self._data = None
self._closed = False
self._sleep_time = sleep_time
def close(self):
self._closed = True
try:
self._semaphore.release()
except:
pass
def send(self, data):
self._semaphore.acquire()
self._data = data
self._semaphore.release()
def stream(self):
while not self._closed:
self._semaphore.acquire()
data = self._data
self._data = None
self._semaphore.release()
if self._closed:
break
if not data is None:
yield data
# make sure that we don't busy wait too much
sleep(self._sleep_time)
# vim: expandtab:ts=2:sw=2:
@silkentrance
Copy link
Author

silkentrance commented Apr 8, 2017

This will give you the ability to implement

  • unary stream
  • stream stream
  • stream unary

based clients and services using Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment