testWebserver所有类分析

发布于:2024-04-16 ⋅ 阅读:(156) ⋅ 点赞:(0)

EventLoop

智能指针

继承std::enable_shared_from_this

为什么要这么继承:
因为EventLoop在别的类中会被shared_ptr管理,并且在loop()函数中被作为参数参与到wpChannel_的构造函数中去

拥有的共享指针对象

SP_Channel wakeupChannel_
SP_Epoll poller_

互斥锁

需要互斥锁来保护共享资源 std::vector<Functor> pendingFunctors_ ,因为loop()函数中将 wakeChannel_ 的 setReadHandler() 与 doPendingFunctors() 绑定,而 doPendingFunctors() 中会操作pendingFunctors_数组,而 queueInLoop() 也会操作pendingFunctors_数组,这两个函数有可能会同时运行,因此需要使用互斥锁来保护pendingFunctors_数组

queueInLoop()

将形参中Functor &&cb放入pendingFunctors_数组中时需要使用互斥锁

void EventLoop::queueInLoop(Functor &&cb) {
    {
        std::lock_guard<std::mutex> lock(mutex_);
        pendingFunctors_.emplace_back(std::move(cb));
    }
    ...
}

doPendingFunctors()

将pendingFunctors_数组中的数据转移到nextPendingFunctors数组中时需要使用互斥锁

void EventLoop::doPendingFunctors() {
    ...

    // 把pendingFunctors_中的数据转移到nextPendingFunctors中,
    // 如果不转移出来,那么在互斥锁加持下,我们直接遍历pendingFunctors_,其他线程这个时候无法访问,无法向里面注册回调函数,增加服务器时延
    std::vector<Functor> nextPendingFunctors;
    {
        std::lock_guard<std::mutex> lock(mutex_);
        nextPendingFunctors.swap(pendingFunctors_);
    }
    for (auto &functor : nextPendingFunctors) {
        functor();
    }
}

Epoll

对epoll多路复用进行封装

负责对管理的事件进行增删改,以及更新管理事件中的就绪事件

Channel

一个Channel对象对应一个epoll_event

负责对epoll_event的事件的函数执行

成员变量

成员函数

处理事件的函数

void handleEvent()

void handleClose()

设置对象内管理的数据

void setReadHandler(EventCallBack &&readHandler)

void setWriteHandler(EventCallBack &&writeHandler)

void setCloseHandler(EventCallBack &&closeHandler)

void setFd(int fd)

void setEvents(int events)

void setRevents(int revents)

void setDeleted(bool deleted)

void setSSL(SP_SSL ssl)

void setSSLConnect(bool sslConnect)

获取对象内管理的数据

int getFd()

int getRevents()

bool isDeleted()

SP_SSL getSSL()

eventfd