1// excerpts from http://code.google.com/p/muduo/
2//
3// Use of this source code is governed by a BSD-style license
4// that can be found in the License file.
5//
6// Author: Shuo Chen (chenshuo at chenshuo dot com)
7
8#include "EventLoop.h"
9
10#include "Channel.h"
11#include "Poller.h"
12
13#include "logging/Logging.h"
14
15#include <assert.h>
16
17using namespace muduo;
18
19__thread EventLoop* t_loopInThisThread = 0;
20const int kPollTimeMs = 10000;
21
22EventLoop::EventLoop()
23  : looping_(false),
24    quit_(false),
25    threadId_(CurrentThread::tid()),
26    poller_(new Poller(this))
27{
28  LOG_TRACE << "EventLoop created " << this << " in thread " << threadId_;
29  if (t_loopInThisThread)
30  {
31    LOG_FATAL << "Another EventLoop " << t_loopInThisThread
32              << " exists in this thread " << threadId_;
33  }
34  else
35  {
36    t_loopInThisThread = this;
37  }
38}
39
40EventLoop::~EventLoop()
41{
42  assert(!looping_);
43  t_loopInThisThread = NULL;
44}
45
46void EventLoop::loop()
47{
48  assert(!looping_);
49  assertInLoopThread();
50  looping_ = true;
51  quit_ = false;
52
53  while (!quit_)
54  {
55    activeChannels_.clear();
56    poller_->poll(kPollTimeMs, &activeChannels_);
57    for (ChannelList::iterator it = activeChannels_.begin();
58        it != activeChannels_.end(); ++it)
59    {
60      (*it)->handleEvent();
61    }
62  }
63
64  LOG_TRACE << "EventLoop " << this << " stop looping";
65  looping_ = false;
66}
67
68void EventLoop::quit()
69{
70  quit_ = true;
71  // wakeup();
72}
73
74void EventLoop::updateChannel(Channel* channel)
75{
76  assert(channel->ownerLoop() == this);
77  assertInLoopThread();
78  poller_->updateChannel(channel);
79}
80
81void EventLoop::abortNotInLoopThread()
82{
83  LOG_FATAL << "EventLoop::abortNotInLoopThread - EventLoop " << this
84            << " was created in threadId_ = " << threadId_
85            << ", current thread id = " <<  CurrentThread::tid();
86}
87
88