chenshuo / muduo

Event-driven network library for multi-threaded Linux server in C++11
https://github.com/chenshuo/muduo
Other
14.7k stars 5.15k forks source link

想请教一下TcpConnection::handleClose这个版本是做出了什么考量 #551

Closed XiaoHuoZZ closed 2 years ago

XiaoHuoZZ commented 2 years ago

之前我看硕神的书handleClose逻辑是这样

void TcpConnection::handleClose() {
    loop_->assertInLoopThread();
    LOG_TRACE("TcpConnection::handleClose state = {}", stateToString());
    assert(state_ == kConnected);

    channel_->disableAll();

    /**
     * 通知TcpServer或TcpClient移除所持有的连接
     */
    closeCallback_(shared_from_this());
}

此时handleClose的职责可以很好理解,就是负责调用closeCallback(甚至我认为channel->disableAll()只在TcpConnection::connectDestroyed() 这里面做就可以了)

而最新版TcpConnection::handleClose是这样

void TcpConnection::handleClose()
{
  loop_->assertInLoopThread();
  LOG_TRACE << "fd = " << channel_->fd() << " state = " << stateToString();
  assert(state_ == kConnected || state_ == kDisconnecting);
  // we don't close fd, leave it to dtor, so we can find leaks easily.
  setState(kDisconnected);
  channel_->disableAll();
  TcpConnectionPtr guardThis(shared_from_this());
  connectionCallback_(guardThis);
  // must be the last line
  closeCallback_(guardThis);
}

可以看到原本应该TcpConnection::connectDestroyed() 做的setState, 执行用户回调connectionCallback 和channel->diaableAll() 提前让handleClose执行了

这让我感觉有些困惑,因为这些操作完全可以等到TcpConnection::connectDestroyed()里面来做

请问各位大神这样的设计的目的是什么

XiaoHuoZZ commented 2 years ago

我想我有点理解了 只所以setState()等操作要提前到handleClose在做 是因为TcpConnection::connectDestroyed() 是延迟到Loop结束后执行的 而调用handleClose之后可能还会调用其他函数, 而其他函数可能视连接关闭而做出其他反应