美文网首页浅析muduo网络库程序员
浅析muduo网络库之EventLoopThread

浅析muduo网络库之EventLoopThread

作者: 谢昆明 | 来源:发表于2018-01-10 12:13 被阅读85次

    看头文件

    class EventLoopThread : boost::noncopyable
    {
     public:
      typedef boost::function<void(EventLoop*)> ThreadInitCallback;
    
      EventLoopThread(const ThreadInitCallback& cb = ThreadInitCallback(),
                      const string& name = string());
      ~EventLoopThread();
      EventLoop* startLoop();
    }
    

    最简单的用法就两行

    EventLoopThread  thread;
    thread.startLoop()
    

    看看怎么实现的

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

    ctor有一行关键代码
    thread_(boost::bind(&EventLoopThread::threadFunc, this), name),
    指定了主循环函数,也就是如下代码

    
    void EventLoopThread::threadFunc()
    {
      EventLoop loop;
    
      if (callback_)
      {
        callback_(&loop);
      }
    
      {
        MutexLockGuard lock(mutex_);
        loop_ = &loop;
        cond_.notify();
      }
    
      loop.loop();
      //assert(exiting_);
      loop_ = NULL;
    }
    

    这边有一个cond_.notify();
    那其他地方肯定在wait()

    找找wait在哪里

    
    EventLoop* EventLoopThread::startLoop()
    {
      assert(!thread_.started());
      thread_.start();
    
      {
        MutexLockGuard lock(mutex_);
        while (loop_ == NULL)
        {
          cond_.wait();
        }
      }
    
      return loop_;
    }
    

    Find!
    startLoop里面启动了线程thread_.start();
    等待线程启动完成,因此有了个wait()
    启动完成的标志是loop_ != NULL

    打赏

    如果这篇文章解决了您的问题,让我买根烟抽抽。

    支付宝.jpg 微信.jpg

    相关文章

      网友评论

        本文标题:浅析muduo网络库之EventLoopThread

        本文链接:https://www.haomeiwen.com/subject/jutonxtx.html