Asynchronous Basics - C++

This tutorial shows you how to write a simple server and client in C++ usinggRPC’s asynchronous/non-blocking APIs. It assumes you are already familiar withwriting simple synchronous gRPC code, as described ingRPC Basics:C++. The example used in this tutorial follows onfrom the basicGreeter example we used in theoverview. You’ll find it along with installationinstructions ingrpc/examples/cpp/helloworld.

Overview

gRPC uses theCompletionQueueAPI for asynchronous operations. The basic work flowis as follows:

  • bind a CompletionQueue to an RPC call
  • do something like a read or write, present with a unique void* tag
  • call CompletionQueue::Next to wait for operations to complete. If a tagappears, it indicates that the corresponding operation is complete.

Async client

To use an asynchronous client to call a remote method, you first create achannel and stub, just as you do in asynchronousclient. Once you have your stub, you dothe following to make an asynchronous call:

  • Initiate the RPC and create a handle for it. Bind the RPC to aCompletionQueue.
  1. CompletionQueue cq;
  2. std::unique_ptr<ClientAsyncResponseReader<HelloReply> > rpc(
  3. stub_->AsyncSayHello(&context, request, &cq));
  • Ask for the reply and final status, with a unique tag
  1. Status status;
  2. rpc->Finish(&reply, &status, (void*)1);
  • Wait for the completion queue to return the next tag. The reply and status areready once the tag passed into the corresponding Finish() call is returned.
  1. void* got_tag;
  2. bool ok = false;
  3. cq.Next(&got_tag, &ok);
  4. if (ok && got_tag == (void*)1) {
  5. // check reply and status
  6. }

You can see the complete client example ingreeter_async_client.cc.

Async server

The server implementation requests an RPC call with a tag and then waits for thecompletion queue to return the tag. The basic flow for handling an RPCasynchronously is:

  • Build a server exporting the async service
  1. helloworld::Greeter::AsyncService service;
  2. ServerBuilder builder;
  3. builder.AddListeningPort("0.0.0.0:50051", InsecureServerCredentials());
  4. builder.RegisterAsyncService(&service);
  5. auto cq = builder.AddCompletionQueue();
  6. auto server = builder.BuildAndStart();
  • Request one RPC, providing a unique tag
  1. ServerContext context;
  2. HelloRequest request;
  3. ServerAsyncResponseWriter<HelloReply> responder;
  4. service.RequestSayHello(&context, &request, &responder, &cq, &cq, (void*)1);
  • Wait for the completion queue to return the tag. The context, request andresponder are ready once the tag is retrieved.
  1. HelloReply reply;
  2. Status status;
  3. void* got_tag;
  4. bool ok = false;
  5. cq.Next(&got_tag, &ok);
  6. if (ok && got_tag == (void*)1) {
  7. // set reply and status
  8. responder.Finish(reply, status, (void*)2);
  9. }
  • Wait for the completion queue to return the tag. The RPC is finished when thetag is back.
  1. void* got_tag;
  2. bool ok = false;
  3. cq.Next(&got_tag, &ok);
  4. if (ok && got_tag == (void*)2) {
  5. // clean up
  6. }

This basic flow, however, doesn’t take into account the server handling multiplerequests concurrently. To deal with this, our complete async server example usesa CallData object to maintain the state of each RPC, and uses the address ofthis object as the unique tag for the call.

  1. class CallData {
  2. public:
  3. // Take in the "service" instance (in this case representing an asynchronous
  4. // server) and the completion queue "cq" used for asynchronous communication
  5. // with the gRPC runtime.
  6. CallData(Greeter::AsyncService* service, ServerCompletionQueue* cq)
  7. : service_(service), cq_(cq), responder_(&ctx_), status_(CREATE) {
  8. // Invoke the serving logic right away.
  9. Proceed();
  10. }
  11. void Proceed() {
  12. if (status_ == CREATE) {
  13. // As part of the initial CREATE state, we *request* that the system
  14. // start processing SayHello requests. In this request, "this" acts are
  15. // the tag uniquely identifying the request (so that different CallData
  16. // instances can serve different requests concurrently), in this case
  17. // the memory address of this CallData instance.
  18. service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
  19. this);
  20. // Make this instance progress to the PROCESS state.
  21. status_ = PROCESS;
  22. } else if (status_ == PROCESS) {
  23. // Spawn a new CallData instance to serve new clients while we process
  24. // the one for this CallData. The instance will deallocate itself as
  25. // part of its FINISH state.
  26. new CallData(service_, cq_);
  27. // The actual processing.
  28. std::string prefix("Hello ");
  29. reply_.set_message(prefix + request_.name());
  30. // And we are done! Let the gRPC runtime know we've finished, using the
  31. // memory address of this instance as the uniquely identifying tag for
  32. // the event.
  33. responder_.Finish(reply_, Status::OK, this);
  34. status_ = FINISH;
  35. } else {
  36. GPR_ASSERT(status_ == FINISH);
  37. // Once in the FINISH state, deallocate ourselves (CallData).
  38. delete this;
  39. }
  40. }
  41. }

For simplicity the server only uses one completion queue for all events, andruns a main loop in HandleRpcs to query the queue:

  1. void HandleRpcs() {
  2. // Spawn a new CallData instance to serve new clients.
  3. new CallData(&service_, cq_.get());
  4. void* tag; // uniquely identifies a request.
  5. bool ok;
  6. while (true) {
  7. // Block waiting to read the next event from the completion queue. The
  8. // event is uniquely identified by its tag, which in this case is the
  9. // memory address of a CallData instance.
  10. cq_->Next(&tag, &ok);
  11. GPR_ASSERT(ok);
  12. static_cast<CallData*>(tag)->Proceed();
  13. }
  14. }

Shutting Down the Server

We’ve been using a completion queue to get the async notifications. Care must betaken to shut it down after the server has also been shut down.

Remember we got our completion queue instance cq in ServerImpl::Run() byrunning cq = builder.AddCompletionQueue(). Looking atServerBuilder::AddCompletionQueue's documentation we see that

… Caller is required to shutdown the server prior to shutting down the returned completion queue.

Refer to ServerBuilder::AddCompletionQueue's full docstring for more details.What this means in our example is that ServerImpl's destructor looks like:

  1. ~ServerImpl() {
  2. server_->Shutdown();
  3. // Always shutdown the completion queue after the server.
  4. cq_->Shutdown();
  5. }

You can see our complete server example ingreeter_async_server.cc.