chenshuo / muduo

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

有关TcpConnection::handleRead中的messageCallback_的小疑问 #555

Closed tomatowithpotato closed 2 years ago

tomatowithpotato commented 2 years ago

我看handleRead函数里会在判断接收到数据后,直接执行回调函数messageCallback_

ssize_t n = inputBuffer_.readFd(channel_->fd(), &savedErrno);
if (n > 0)
{
  messageCallback_(shared_from_this(), &inputBuffer_, receiveTime);
}

但是在handleWrite中,回调函数writeCompleteCallback_是交给queueInLoop来执行的

if (writeCompleteCallback_)
{
  loop_->queueInLoop(std::bind(writeCompleteCallback_, shared_from_this()));
}

为什么会有这种区别呢?求大佬赐教!!!!

chenshuo commented 2 years ago

为了防止 stack overflow,因为 writeCompleteCallback_ 往往会再次调用 TcpConnection::send()。

如果直接调用 writeCompleteCallback_,有可能出现递归:

send("a") -> sendInLoop("a") -> writeCompleteCallback() -> send("b") -> sendInLoop("b") -> writeCompleteCallback() -> send("c") -> sendInLoop("c") -> writeCompleteCallback_() -> ...