send函数是否应该检查isInLoopThread()

文章讨论了在send函数中是否应检查isInLoopThread,以防止在非事件循环线程中调用导致的问题。作者认为,如果send操作可能来自非事件循环线程,检查是必要的,以维护线程安全。
摘要由CSDN通过智能技术生成

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值