You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

连续创建grpc::ClientBidiReactor时程序崩溃问题求助

多次调用gRPC异步双向流客户端方法导致崩溃问题

问题场景

调用SendData连接不存在的服务器时,首次会正确输出failed to connect to all addresses;但多次调用SendData后程序崩溃,错误信息显示纯虚函数调用,最终触发段错误。

代码实现

SendData函数

ErrorCode SendData(const char *data, size_t length)
{
  auto stream = std::make_unique<Stream>(stub_.get(), client_id_, timeout_seconds_);
  return stream->SendMessage(data, length);
}

Stream类定义

class Stream : public grpc::ClientBidiReactor<SendBinaryDataRequest, SendBinaryDataResponse> {
   public:
    Stream(MessageTransfer::Stub *stub)
        : context_(), status_(grpc::Status::OK), done_(false), request_(), response_(), mu_(), cv_()
    {
      stub->async()->SendStreamBinaryDataWithAck(&context_, this);
      StartCall();
      std::cout << "new construtor:" << this << std::endl;
    }

    void OnWriteDone(bool ok) override
    {
      std::unique_lock<std::mutex> l(mu_);
      if (ok) {
        StartRead(&response_);
      }
    }

    void OnWritesDoneDone(bool) override
    {
      std::unique_lock<std::mutex> l(mu_);
      cv_.notify_one();
    }
    
    void OnReadDone(bool ok) override
    {
      std::unique_lock<std::mutex> l(mu_);
      if (ok) {
        cv_.notify_one();
      }
    }

    void OnDone(const grpc::Status &s) override
    {
      std::unique_lock<std::mutex> l(mu_);
      LOG("%p stream closed status:%d error:%s\n", this, s.error_code(), s.error_message().c_str());
      status_ = s;
      done_   = true;
      cv_.notify_one();
    }

    ErrorCode SendMessage(const char *data, size_t length)
    {
      std::unique_lock<std::mutex> l(mu_);

      if (done_) {
        return convertToErrorCode(status_);
      }

      request_.set_data(data, length);
      LOG("StartWrite %p\n", this);
      StartWrite(&request_);
      if(std::cv_status::timeout == cv_.wait_for(l, std::chrono::seconds(timeout_sec_))) {
        return ErrorCode_TIMEOUT;
      }
      if (done_) {
        return convertToErrorCode(status_);
      }
      return static_cast<ErrorCode>(response_.error_code());
    }
};

错误信息与日志

崩溃错误信息

pure virtual method called
terminate called without an active exception
Aborted (core dumped)

运行日志

new construtor:0x168dbc0
StartWrite 0x168dbc0
0x168dbc0 stream closed status:14 error:failed to connect to all addresses; last error: UNKNOWN: unix:/tmp/hs_message.sock: Connection refused
new construtor:0x168dbc0
StartWrite 0x168dbc0
Segmentation fault (core dumped)

补充说明

观察到每次创建的stream指针地址相同,但认为这并非崩溃原因,已附上gdb调试信息截图,恳请帮忙排查问题。

内容的提问来源于stack exchange,提问作者Gavin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 09:37:16