0

I wrote a client which starts multiple connections to a grpc server to request something. I want to stop all the other grpc call once I got a reply. I use an Event to control this process.

However, I don't know how to terminate a grpc call gracefully. The below is what I did. The code will cause an error: too many open files. Can somebody help me? How to terminate a grpc call gracefully?

def request_something(event):
    with grpc.insecure_channel(ip) as channel:
        stub = GrpcServiceStub(channel)
        req = Request()
        response_future = stub.GetResponse.future(req)

        while not response_future.done() and not event.is_set():
            time.sleep(0.1)

        if event.is_set():
            # try to interrupt grpc call
            if not response_future.cancel():
                while not response_future.done():
                    time.sleep(0.1)
            print("Stop request")
            channel.close()
            return

        response = response_future.result()
    return response


event = Event()
with futures.ThreadPoolExecutor(max_workers=...) as executor:
     res = []
     for _ in range(...):
         future = executor.submit(request_something, event)
         res.append(future)
         for future in futures.as_completed(res):
             print("now we get the first response")
             event.set()
             executor.shutdown(wait=False)
mageover
  • 21
  • 4

1 Answers1

1

You could use the future API on your client calls (https://grpc.github.io/grpc/python/grpc.html#grpc.UnaryUnaryMultiCallable.future) and then call cancel on the futures (https://grpc.github.io/grpc/python/grpc.html#grpc.Future.cancel).

Full cancellation example in Python: https://github.com/grpc/grpc/tree/master/examples/python/cancellation

Hope this helps!