Memory leak possibility in greeter_async_client2.cc?

52 views
Skip to first unread message

zhju...@gmail.com

unread,
Jul 24, 2019, 9:43:47 PM7/24/19
to grpc.io
Hi,

I'm trying to write an async grpc client and looking into greeter async example.


In the SayHello function, it new an AsyncClientCall object and then pass the object  to the  Finish function.

// Assembles the client's payload and sends it to the server.
void SayHello(const std::string& user) {
    // Data we are sending to the server.
    HelloRequest request;
    request.set_name(user);

    // Call object to store rpc data
    AsyncClientCall* call = new AsyncClientCall;

    // stub_->PrepareAsyncSayHello() creates an RPC object, returning
    // an instance to store in "call" but does not actually start the RPC
    // Because we are using the asynchronous API, we need to hold on to
    // the "call" instance in order to get updates on the ongoing RPC.
    call->response_reader =
        stub_->PrepareAsyncSayHello(&call->context, request, &cq_);

    // StartCall initiates the RPC call
    call->response_reader->StartCall();

    // Request that, upon completion of the RPC, "reply" be updated with the
    // server's response; "status" with the indication of whether the operation
    // was successful. Tag the request with the memory address of the call object.
    call->response_reader->Finish(&call->reply, &call->status, (void*)call);

}

In the function AsyncCompleteRpc, it casts the object back to AsyncClientCall  and delete the object.

// Loop while listening for completed responses.
// Prints out the response from the server.
void AsyncCompleteRpc() {
    void* got_tag;
    bool ok = false;

    // Block until the next result is available in the completion queue "cq".
    while (cq_.Next(&got_tag, &ok)) {
        // The tag in this example is the memory location of the call object
        AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);

        ...


        // Once we're complete, deallocate the call object.
        delete call;

So my question is, is there any possibility that function  AsyncCompleteRpc doesn't have chance to receive the message in cq_, which lead to memory leak?

I mean an object newed in the function SayHello, does it make sure to be received in function AsyncCompleteRpc,and delete the object?

Thanks a lot!

Yang Gao

unread,
Aug 7, 2019, 1:46:52 PM8/7/19
to grpc.io
grpc completion queue will return all the tags you give it. To avoid the case you talk about, you will need to make sure you drain the completion queue before destroying it.
Reply all
Reply to author
Forward
0 new messages