muduo库 EventLoopThread

#pragma once

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

#include<functional>
#include<mutex>
#include<condition_variable>//条件变量头文件
#include<string>

class EventLoop;

// one loop per thread
class EventLoopThread:noncopyable
{
public:
    using ThreadInitCallback = std::function<void(EventLoop*)>;

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

    EventLoop*startLoop();//开启循环

private:
    //线程函数,在里面创建loop
    void threadFunc();

    EventLoop*loop_;
    bool exiting_; //是否退出循环
    Thread thread_;
    std::mutex mutex_;//互斥锁
    std::condition_variable cond_;//条件变量
    ThreadInitCallback callback_;
};
#include"EventLoopThread.h"
#include"EventLoop.h"
#include"Logger.h"

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

}

EventLoopThread::~EventLoopThread()
{
    //意思是线程要退出了,也要将其事件循环loop退出
    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)//修改了此处,从loop变成loop_
        {
            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

    std::unique_lock<std::mutex> lock(mutex_);
    loop_=nullptr;
}

//对startLoop函数和threadFunc函数之间关系的理解
/*
*   在构造EventLoopThread时(详见其构造函数),已经将threadFunc函数绑定给Thread下面的func函数;
*   当调用startLoop函数时,里面的 thread.start() 将创建一个线程,同时调用其func函数(已绑定了threadFunc)(详见thread下的start函数)
*   threadFunc将正式生成一个EvenLoop,
*   startLoop中生成的EventLoop* loop指针暂时设置为空,
*   (其实该函数最后要返回真正工作的EventLoop,即threadFunc函数中生成的EventLoop.沟通方法即EventLoopThread下面的loop_)
*   因此用上条件变量,将startLoop中的loop锁起来,等待threadFunc函数中,loop_ = &loop,然后再唤醒startLoop中的条件变量
*   这样将startLoop中的loop指针就可以指向 loop_了(loop=loop_),然后再return  loop;
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值