2023-12-28 muduo库学习之仿写代码9 事件线程类

EventLoopThread.h

这个EventLoopThread就是对应之前说的one loop per thread,让一个loop绑定一个线程

#pragma once

#include "noncopyable.h"
#include "Thread.h"
#include "EventLoop.h"

#include <functional>
#include <mutex>
#include <condition_variable>
#include <string>

class EventLoop;

class EventLoopThread : noncopyable {
public:
    using ThreadInitCallback = std::functional<void(EventLoop*)>;

    EventLoopThread(const ThreadInitCallback &cb = ThreadInitCallback(), const std::string &name = std::string());
    ~EventLoopThread();

    EventLoop* startLoop();

private:

    void threadFunc();

    EventLoop *loop_;
    bool exiting_;
    Thread thread_;
    std::mutex mutex_;
    std::condition_variable cond_;
    ThreadInitCallback callback_;
};

EventLoopThread.cc

#include "EventLoopThread.h"

EventLoopThread::EventLoopThread(const ThreadInitCallback &cb = ThreadInitCallback()
    , const std::string &name = std::string())
    : loop_(nullptr)
    , exiting_(false)
    , thread_(std::bind(&EventLoopThread::threadFunc, this), name)
    , mutex_(), cond_(), callback_(cb) {

}

EventLoopThread::~EventLoopThread(){
    exiting_ = true;
    if(loop_ != nullptr) {
        loop_->quit();
        thread_.join();
    }
}

EventLoop* EventLoopThread::startLoop(){
    thread_.start(); //启动底层的新线程

    EventLoop* loop = nullptr;

    {
        std::unique_lock<std::mutex> lock(mutex_);
        while (loop_ == nullptr)
        {
            cond_.wait(lock);
        }
        loop = loop_;
    }
    return loop;
}

// 下面这个方法,是在单独的新线程里面运行的
void EventLoopThread::threadFunc() {
    EventLoop loop; //创建一个独立的eventloop,和上面的线程是一一对应的 ,one loop per thread

    if(callback_) {
        callback_(&loop);
    }

    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }

    loop.loop(); //EventLoop loop => Poller.poll
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容