【问题标题】:Memory leak in gRPC async_clientgRPC async_client 中的内存泄漏
【发布时间】:2023-03-15 21:45:01
【问题描述】:

我使用gRPC async client 的方式与example 类似。

在这个例子中(发布在gRPC官方github)客户端为要发送的消息分配内存,使用地址为tagcompletion queue,并且当消息在监听器中被应答时线程内存(由tag- 地址知道)是空闲的。

我担心服务器没有响应消息并且内存永远不会空闲的情况。

  • gRPC 是否可以保护我免受这种情况的影响?
  • 我应该以不同的方式实现它吗? (使用智能指针/将指针保存在数据结构中/等...)

异步客户端发送功能

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;

    // 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();

    call->response_reader->Finish(&call->reply, &call->status, (void*)call);

}

线程的异步客户端接收函数

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);

        // Verify that the request was completed successfully. Note that "ok"
        // corresponds solely to the request for updates introduced by Finish().
        GPR_ASSERT(ok);

        if (call->status.ok())
            std::cout << "Greeter received: " << call->reply.message() << std::endl;
        else
            std::cout << "RPC failed" << std::endl;

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

主要

int main(int argc, char** argv) {


    GreeterClient greeter(grpc::CreateChannel(
            "localhost:50051", grpc::InsecureChannelCredentials()));

    // Spawn reader thread that loops indefinitely
    std::thread thread_ = std::thread(&GreeterClient::AsyncCompleteRpc, &greeter);

    for (int i = 0; i < 100; i++) {
        std::string user("world " + std::to_string(i));
        greeter.SayHello(user);  // The actual RPC call!
    }

    std::cout << "Press control-c to quit" << std::endl << std::endl;
    thread_.join();  //blocks forever

    return 0;
}

【问题讨论】:

    标签: c++ memory-leaks grpc grpc-c++


    【解决方案1】:

    gRPC 是否可以保护我免受这种情况的影响?

    有点。 gRPC 保证所有排队的操作迟早都会进入其匹配的完成队列。所以你的代码是可以的,只要:

    • 在不幸的时候不会抛出异常。
    • 您不要对创建代码路径的代码进行更改,其中不包括对操作进行排队或删除调用。

    换句话说:没关系,但很脆弱。

    选项A:

    如果您想变得真正健壮,那么要走的路是std::shared_ptr&lt;&gt;。但是,它们可能会以意想不到的方式影响多线程性能。因此,是否值得取决于您的应用在性能与鲁棒性范围内的位置。

    这样的重构看起来像:

    1. AsyncClientCall 继承自std::enable_shared_from_this
    2. call的结构改为std::make_shared&lt;AsyncClientCall&gt;()
    3. 在完成队列处理程序中,增加引用计数:
    while (cq_.Next(&got_tag, &ok)) {
        auto call = static_cast<AsyncClientCall*>(got_tag)->shared_from_this();
    

    显然,摆脱delete

    选项B:

    您还可以通过unique_ptr&lt;&gt; 获得一个不错的中途测量:

        auto call = std::make_unique<AsyncClientCall>();
        ...
        call->response_reader->Finish(&call->reply, &call->status, (void*)call.release());
    

        std::unique_ptr<AsyncClientCall> call{static_cast<AsyncClientCall*>(got_tag)};
    

    这可以防止重构和异常,同时维护其他所有内容。但是,这仅适用于产生单个完成事件的一元 RPC。流式 RPC 或交换元数据的 RPC 将需要完全不同的处理方式。

    【讨论】:

    • 感谢您的回答,如果服务器没有响应某些消息,会发生什么情况?消息会留在队列中等待吗?队列会溢出吗?在这种情况下,我们可以从旧消息中清除队列吗?
    • @lior.i 如果服务器没有响应,RPC 迟早会失败,要么超时,要么套接字关闭,要么以某种方式取消。此时,标签将被放入队列中,状态为 non-ok。
    • "在这种情况下我们可以清除队列中的旧消息吗?"您可以随时取消通话。但一般来说,添加最后期限就足够了。
    • 取消通话是什么意思?
    • TryCancel(),但正如我所说,set_deadline() 通常是首选,因为它是一劳永逸的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    相关资源
    最近更新 更多