send函数是否应该检查isInLoopThread()
结论:应该检查,因为我报错了。
起因:因为我发现runinloop里面也有isinloopthread的检查,所以我认为直接runinloop就好了,但是不行。
chat:这是一个设计上的考量,如果send上下文不会涉及多线程,就不用检查。但如果有不是来自于事件循环线程的调用,那就需要检查。
send函数:
不报错代码
void TcpConnection::send(const std::string &buf)
{
if (state_ == kConnected)
{
if (loop_->isInLoopThread())//对是否在线程进行了判断
{
sendInLoop(buf.c_str(), buf.size());
}
else
{
loop_->runInLoop(
std::bind(
&TcpConnection::sendInLoop,
this,
buf.c_str(),
buf.size()));
}
}
}
报错代码:
void TcpConnection::send(const std::string &buf)
{
if (state_ == kConnected)
{
loop_->runInLoop(
std::bind(&TcpConnection::sendInLoop, this, buf.c_str(), buf.size()));
}
}
runinloop函数
void EventLoop::runInLoop(Functor cb)
{
if (isInLoopThread())
{
cb();
}
else // 在非当前loop线程中执行cb
{
queueInLoop(cb);
}
}