std::chrono'ize EventBase::loopBody
[folly.git] / folly / io / async / EventBase.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef __STDC_FORMAT_MACROS
18 #define __STDC_FORMAT_MACROS
19 #endif
20
21 #include <folly/io/async/EventBase.h>
22
23 #include <folly/ThreadName.h>
24 #include <folly/io/async/NotificationQueue.h>
25 #include <folly/portability/Unistd.h>
26
27 #include <condition_variable>
28 #include <fcntl.h>
29 #include <mutex>
30 #include <pthread.h>
31
32 namespace folly {
33
34 /*
35  * EventBase::FunctionRunner
36  */
37
38 class EventBase::FunctionRunner
39     : public NotificationQueue<EventBase::Func>::Consumer {
40  public:
41   void messageAvailable(Func&& msg) override {
42     // In libevent2, internal events do not break the loop.
43     // Most users would expect loop(), followed by runInEventBaseThread(),
44     // to break the loop and check if it should exit or not.
45     // To have similar bejaviour to libevent1.4, tell the loop to break here.
46     // Note that loop() may still continue to loop, but it will also check the
47     // stop_ flag as well as runInLoop callbacks, etc.
48     event_base_loopbreak(getEventBase()->evb_);
49
50     if (!msg) {
51       // terminateLoopSoon() sends a null message just to
52       // wake up the loop.  We can ignore these messages.
53       return;
54     }
55
56     // The function should never throw an exception, because we have no
57     // way of knowing what sort of error handling to perform.
58     //
59     // If it does throw, log a message and abort the program.
60     try {
61       msg();
62     } catch (const std::exception& ex) {
63       LOG(ERROR) << "runInEventBaseThread() function threw a "
64                  << typeid(ex).name() << " exception: " << ex.what();
65       abort();
66     } catch (...) {
67       LOG(ERROR) << "runInEventBaseThread() function threw an exception";
68       abort();
69     }
70   }
71 };
72
73 // The interface used to libevent is not thread-safe.  Calls to
74 // event_init() and event_base_free() directly modify an internal
75 // global 'current_base', so a mutex is required to protect this.
76 //
77 // event_init() should only ever be called once.  Subsequent calls
78 // should be made to event_base_new().  We can recognise that
79 // event_init() has already been called by simply inspecting current_base.
80 static std::mutex libevent_mutex_;
81
82 /*
83  * EventBase methods
84  */
85
86 EventBase::EventBase(bool enableTimeMeasurement)
87   : runOnceCallbacks_(nullptr)
88   , stop_(false)
89   , loopThread_()
90   , queue_(nullptr)
91   , fnRunner_(nullptr)
92   , maxLatency_(0)
93   , avgLoopTime_(std::chrono::milliseconds(2000000))
94   , maxLatencyLoopTime_(avgLoopTime_)
95   , enableTimeMeasurement_(enableTimeMeasurement)
96   , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
97   , latestLoopCnt_(nextLoopCnt_)
98   , startWork_()
99   , observer_(nullptr)
100   , observerSampleCount_(0)
101   , executionObserver_(nullptr) {
102   struct event ev;
103   {
104     std::lock_guard<std::mutex> lock(libevent_mutex_);
105
106     // The value 'current_base' (libevent 1) or
107     // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
108     // allowing examination of its value without an explicit reference here.
109     // If ev.ev_base is NULL, then event_init() must be called, otherwise
110     // call event_base_new().
111     event_set(&ev, 0, 0, nullptr, nullptr);
112     if (!ev.ev_base) {
113       evb_ = event_init();
114     }
115   }
116
117   if (ev.ev_base) {
118     evb_ = event_base_new();
119   }
120
121   if (UNLIKELY(evb_ == nullptr)) {
122     LOG(ERROR) << "EventBase(): Failed to init event base.";
123     folly::throwSystemError("error in EventBase::EventBase()");
124   }
125   VLOG(5) << "EventBase(): Created.";
126   initNotificationQueue();
127   RequestContext::saveContext();
128 }
129
130 // takes ownership of the event_base
131 EventBase::EventBase(event_base* evb, bool enableTimeMeasurement)
132   : runOnceCallbacks_(nullptr)
133   , stop_(false)
134   , loopThread_()
135   , evb_(evb)
136   , queue_(nullptr)
137   , fnRunner_(nullptr)
138   , maxLatency_(0)
139   , avgLoopTime_(std::chrono::milliseconds(2000000))
140   , maxLatencyLoopTime_(avgLoopTime_)
141   , enableTimeMeasurement_(enableTimeMeasurement)
142   , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
143   , latestLoopCnt_(nextLoopCnt_)
144   , startWork_()
145   , observer_(nullptr)
146   , observerSampleCount_(0)
147   , executionObserver_(nullptr) {
148   if (UNLIKELY(evb_ == nullptr)) {
149     LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
150     throw std::invalid_argument("EventBase(): event base cannot be nullptr");
151   }
152   initNotificationQueue();
153   RequestContext::saveContext();
154 }
155
156 EventBase::~EventBase() {
157   // Keep looping until all keep-alive handles are released. Each keep-alive
158   // handle signals that some external code will still schedule some work on
159   // this EventBase (so it's not safe to destroy it).
160   while (loopKeepAliveCount() > 0) {
161     applyLoopKeepAlive();
162     loopOnce();
163   }
164
165   // Call all destruction callbacks, before we start cleaning up our state.
166   while (!onDestructionCallbacks_.empty()) {
167     LoopCallback* callback = &onDestructionCallbacks_.front();
168     onDestructionCallbacks_.pop_front();
169     callback->runLoopCallback();
170   }
171
172   clearCobTimeouts();
173
174   DCHECK_EQ(0, runBeforeLoopCallbacks_.size());
175
176   (void)runLoopCallbacks();
177
178   if (!fnRunner_->consumeUntilDrained()) {
179     LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
180   }
181
182   // Stop consumer before deleting NotificationQueue
183   fnRunner_->stopConsuming();
184   {
185     std::lock_guard<std::mutex> lock(libevent_mutex_);
186     event_base_free(evb_);
187   }
188
189   {
190     std::lock_guard<std::mutex> lock(localStorageMutex_);
191     for (auto storage : localStorageToDtor_) {
192       storage->onEventBaseDestruction(*this);
193     }
194   }
195   VLOG(5) << "EventBase(): Destroyed.";
196 }
197
198 size_t EventBase::getNotificationQueueSize() const {
199   return queue_->size();
200 }
201
202 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
203   fnRunner_->setMaxReadAtOnce(maxAtOnce);
204 }
205
206 // Set smoothing coefficient for loop load average; input is # of milliseconds
207 // for exp(-1) decay.
208 void EventBase::setLoadAvgMsec(std::chrono::milliseconds ms) {
209   assert(enableTimeMeasurement_);
210   std::chrono::microseconds us = std::chrono::milliseconds(ms);
211   if (ms > std::chrono::milliseconds::zero()) {
212     maxLatencyLoopTime_.setTimeInterval(us);
213     avgLoopTime_.setTimeInterval(us);
214   } else {
215     LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
216   }
217 }
218
219 void EventBase::resetLoadAvg(double value) {
220   assert(enableTimeMeasurement_);
221   avgLoopTime_.reset(value);
222   maxLatencyLoopTime_.reset(value);
223 }
224
225 static std::chrono::milliseconds
226 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
227   auto result = std::chrono::steady_clock::now() - *prev;
228   *prev = std::chrono::steady_clock::now();
229
230   return std::chrono::duration_cast<std::chrono::milliseconds>(result);
231 }
232
233 void EventBase::waitUntilRunning() {
234   while (!isRunning()) {
235     sched_yield();
236   }
237 }
238
239 // enters the event_base loop -- will only exit when forced to
240 bool EventBase::loop() {
241   return loopBody();
242 }
243
244 bool EventBase::loopOnce(int flags) {
245   return loopBody(flags | EVLOOP_ONCE);
246 }
247
248 bool EventBase::loopBody(int flags) {
249   VLOG(5) << "EventBase(): Starting loop.";
250
251   DCHECK(!invokingLoop_)
252       << "Your code just tried to loop over an event base from inside another "
253       << "event base loop. Since libevent is not reentrant, this leads to "
254       << "undefined behavior in opt builds. Please fix immediately. For the "
255       << "common case of an inner function that needs to do some synchronous "
256       << "computation on an event-base, replace getEventBase() by a new, "
257       << "stack-allocated EvenBase.";
258   invokingLoop_ = true;
259   SCOPE_EXIT {
260     invokingLoop_ = false;
261   };
262
263   int res = 0;
264   bool ranLoopCallbacks;
265   bool blocking = !(flags & EVLOOP_NONBLOCK);
266   bool once = (flags & EVLOOP_ONCE);
267
268   // time-measurement variables.
269   std::chrono::steady_clock::time_point prev;
270   std::chrono::steady_clock::time_point idleStart = {};
271   std::chrono::microseconds busy;
272   std::chrono::microseconds idle;
273
274   loopThread_.store(pthread_self(), std::memory_order_release);
275
276   if (!name_.empty()) {
277     setThreadName(name_);
278   }
279
280   if (enableTimeMeasurement_) {
281     prev = std::chrono::steady_clock::now();
282     idleStart = std::chrono::steady_clock::now();
283   }
284
285   while (!stop_.load(std::memory_order_acquire)) {
286     applyLoopKeepAlive();
287     ++nextLoopCnt_;
288
289     // Run the before loop callbacks
290     LoopCallbackList callbacks;
291     callbacks.swap(runBeforeLoopCallbacks_);
292
293     while(!callbacks.empty()) {
294       auto* item = &callbacks.front();
295       callbacks.pop_front();
296       item->runLoopCallback();
297     }
298
299     // nobody can add loop callbacks from within this thread if
300     // we don't have to handle anything to start with...
301     if (blocking && loopCallbacks_.empty()) {
302       res = event_base_loop(evb_, EVLOOP_ONCE);
303     } else {
304       res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
305     }
306
307     ranLoopCallbacks = runLoopCallbacks();
308
309     if (enableTimeMeasurement_) {
310       busy = std::chrono::duration_cast<std::chrono::microseconds>(
311           std::chrono::steady_clock::now() - startWork_);
312       idle = std::chrono::duration_cast<std::chrono::microseconds>(
313           startWork_ - idleStart);
314
315       avgLoopTime_.addSample(std::chrono::microseconds(idle),
316         std::chrono::microseconds(busy));
317       maxLatencyLoopTime_.addSample(std::chrono::microseconds(idle),
318         std::chrono::microseconds(busy));
319
320       if (observer_) {
321         if (observerSampleCount_++ == observer_->getSampleRate()) {
322           observerSampleCount_ = 0;
323           observer_->loopSample(busy.count(), idle.count());
324         }
325       }
326
327       VLOG(11) << "EventBase "  << this         << " did not timeout " <<
328         " loop time guess: "    << (busy + idle).count()  <<
329         " idle time: "          << idle.count()         <<
330         " busy time: "          << busy.count()         <<
331         " avgLoopTime: "        << avgLoopTime_.get() <<
332         " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
333         " maxLatency_: "        << maxLatency_.count() << "us" <<
334         " notificationQueueSize: " << getNotificationQueueSize() <<
335         " nothingHandledYet(): " << nothingHandledYet();
336
337       // see if our average loop time has exceeded our limit
338       if ((maxLatency_ > std::chrono::microseconds::zero()) &&
339           (maxLatencyLoopTime_.get() > double(maxLatency_.count()))) {
340         maxLatencyCob_();
341         // back off temporarily -- don't keep spamming maxLatencyCob_
342         // if we're only a bit over the limit
343         maxLatencyLoopTime_.dampen(0.9);
344       }
345
346       // Our loop run did real work; reset the idle timer
347       idleStart = std::chrono::steady_clock::now();
348     } else {
349       VLOG(11) << "EventBase " << this << " did not timeout";
350     }
351
352     // If the event loop indicate that there were no more events, and
353     // we also didn't have any loop callbacks to run, there is nothing left to
354     // do.
355     if (res != 0 && !ranLoopCallbacks) {
356       // Since Notification Queue is marked 'internal' some events may not have
357       // run.  Run them manually if so, and continue looping.
358       //
359       if (getNotificationQueueSize() > 0) {
360         fnRunner_->handlerReady(0);
361       } else {
362         break;
363       }
364     }
365
366     if (enableTimeMeasurement_) {
367       VLOG(5) << "EventBase " << this << " loop time: " <<
368         getTimeDelta(&prev).count();
369     }
370
371     if (once) {
372       break;
373     }
374   }
375   // Reset stop_ so loop() can be called again
376   stop_ = false;
377
378   if (res < 0) {
379     LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
380     return false;
381   } else if (res == 1) {
382     VLOG(5) << "EventBase: ran out of events (exiting loop)!";
383   } else if (res > 1) {
384     LOG(ERROR) << "EventBase: unknown event loop result = " << res;
385     return false;
386   }
387
388   loopThread_.store({}, std::memory_order_release);
389
390   VLOG(5) << "EventBase(): Done with loop.";
391   return true;
392 }
393
394 ssize_t EventBase::loopKeepAliveCount() {
395   if (loopKeepAliveCountAtomic_.load(std::memory_order_relaxed)) {
396     loopKeepAliveCount_ +=
397         loopKeepAliveCountAtomic_.exchange(0, std::memory_order_relaxed);
398   }
399   DCHECK_GE(loopKeepAliveCount_, 0);
400   return loopKeepAliveCount_;
401 }
402
403 void EventBase::applyLoopKeepAlive() {
404   if (loopKeepAliveActive_ && loopKeepAliveCount() == 0) {
405     // Restore the notification queue internal flag
406     fnRunner_->stopConsuming();
407     fnRunner_->startConsumingInternal(this, queue_.get());
408     loopKeepAliveActive_ = false;
409   } else if (!loopKeepAliveActive_ && loopKeepAliveCount() > 0) {
410     // Update the notification queue event to treat it as a normal
411     // (non-internal) event.  The notification queue event always remains
412     // installed, and the main loop won't exit with it installed.
413     fnRunner_->stopConsuming();
414     fnRunner_->startConsuming(this, queue_.get());
415     loopKeepAliveActive_ = true;
416   }
417 }
418
419 void EventBase::loopForever() {
420   bool ret;
421   {
422     SCOPE_EXIT {
423       applyLoopKeepAlive();
424     };
425     // Make sure notification queue events are treated as normal events.
426     // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
427     // released inside a loop.
428     ++loopKeepAliveCount_;
429     SCOPE_EXIT {
430       --loopKeepAliveCount_;
431     };
432     ret = loop();
433   }
434
435   if (!ret) {
436     folly::throwSystemError("error in EventBase::loopForever()");
437   }
438 }
439
440 void EventBase::bumpHandlingTime() {
441   if (!enableTimeMeasurement_) {
442     return;
443   }
444
445   VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
446     " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
447   if (nothingHandledYet()) {
448     latestLoopCnt_ = nextLoopCnt_;
449     // set the time
450     startWork_ = std::chrono::steady_clock::now();
451
452     VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
453              << " (loop) startWork_ " << startWork_.time_since_epoch().count();
454   }
455 }
456
457 void EventBase::terminateLoopSoon() {
458   VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
459
460   // Set stop to true, so the event loop will know to exit.
461   // TODO: We should really use an atomic operation here with a release
462   // barrier.
463   stop_ = true;
464
465   // Call event_base_loopbreak() so that libevent will exit the next time
466   // around the loop.
467   event_base_loopbreak(evb_);
468
469   // If terminateLoopSoon() is called from another thread,
470   // the EventBase thread might be stuck waiting for events.
471   // In this case, it won't wake up and notice that stop_ is set until it
472   // receives another event.  Send an empty frame to the notification queue
473   // so that the event loop will wake up even if there are no other events.
474   //
475   // We don't care about the return value of trySendFrame().  If it fails
476   // this likely means the EventBase already has lots of events waiting
477   // anyway.
478   try {
479     queue_->putMessage(nullptr);
480   } catch (...) {
481     // We don't care if putMessage() fails.  This likely means
482     // the EventBase already has lots of events waiting anyway.
483   }
484 }
485
486 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
487   DCHECK(isInEventBaseThread());
488   callback->cancelLoopCallback();
489   callback->context_ = RequestContext::saveContext();
490   if (runOnceCallbacks_ != nullptr && thisIteration) {
491     runOnceCallbacks_->push_back(*callback);
492   } else {
493     loopCallbacks_.push_back(*callback);
494   }
495 }
496
497 void EventBase::runInLoop(Func cob, bool thisIteration) {
498   DCHECK(isInEventBaseThread());
499   auto wrapper = new FunctionLoopCallback(std::move(cob));
500   wrapper->context_ = RequestContext::saveContext();
501   if (runOnceCallbacks_ != nullptr && thisIteration) {
502     runOnceCallbacks_->push_back(*wrapper);
503   } else {
504     loopCallbacks_.push_back(*wrapper);
505   }
506 }
507
508 void EventBase::runOnDestruction(LoopCallback* callback) {
509   std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
510   callback->cancelLoopCallback();
511   onDestructionCallbacks_.push_back(*callback);
512 }
513
514 void EventBase::runBeforeLoop(LoopCallback* callback) {
515   DCHECK(isInEventBaseThread());
516   callback->cancelLoopCallback();
517   runBeforeLoopCallbacks_.push_back(*callback);
518 }
519
520 bool EventBase::runInEventBaseThread(Func fn) {
521   // Send the message.
522   // It will be received by the FunctionRunner in the EventBase's thread.
523
524   // We try not to schedule nullptr callbacks
525   if (!fn) {
526     LOG(ERROR) << "EventBase " << this
527                << ": Scheduling nullptr callbacks is not allowed";
528     return false;
529   }
530
531   // Short-circuit if we are already in our event base
532   if (inRunningEventBaseThread()) {
533     runInLoop(std::move(fn));
534     return true;
535
536   }
537
538   try {
539     queue_->putMessage(std::move(fn));
540   } catch (const std::exception& ex) {
541     LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
542                << "for EventBase thread: " << ex.what();
543     return false;
544   }
545
546   return true;
547 }
548
549 bool EventBase::runInEventBaseThreadAndWait(FuncRef fn) {
550   if (inRunningEventBaseThread()) {
551     LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
552                << "allowed";
553     return false;
554   }
555
556   bool ready = false;
557   std::mutex m;
558   std::condition_variable cv;
559   runInEventBaseThread([&] {
560       SCOPE_EXIT {
561         std::unique_lock<std::mutex> l(m);
562         ready = true;
563         cv.notify_one();
564         // We cannot release the lock before notify_one, because a spurious
565         // wakeup in the waiting thread may lead to cv and m going out of scope
566         // prematurely.
567       };
568       fn();
569   });
570   std::unique_lock<std::mutex> l(m);
571   cv.wait(l, [&] { return ready; });
572
573   return true;
574 }
575
576 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(FuncRef fn) {
577   if (isInEventBaseThread()) {
578     fn();
579     return true;
580   } else {
581     return runInEventBaseThreadAndWait(std::move(fn));
582   }
583 }
584
585 bool EventBase::runLoopCallbacks() {
586   if (!loopCallbacks_.empty()) {
587     bumpHandlingTime();
588     // Swap the loopCallbacks_ list with a temporary list on our stack.
589     // This way we will only run callbacks scheduled at the time
590     // runLoopCallbacks() was invoked.
591     //
592     // If any of these callbacks in turn call runInLoop() to schedule more
593     // callbacks, those new callbacks won't be run until the next iteration
594     // around the event loop.  This prevents runInLoop() callbacks from being
595     // able to start file descriptor and timeout based events.
596     LoopCallbackList currentCallbacks;
597     currentCallbacks.swap(loopCallbacks_);
598     runOnceCallbacks_ = &currentCallbacks;
599
600     while (!currentCallbacks.empty()) {
601       LoopCallback* callback = &currentCallbacks.front();
602       currentCallbacks.pop_front();
603       folly::RequestContextScopeGuard rctx(callback->context_);
604       callback->runLoopCallback();
605     }
606
607     runOnceCallbacks_ = nullptr;
608     return true;
609   }
610   return false;
611 }
612
613 void EventBase::initNotificationQueue() {
614   // Infinite size queue
615   queue_.reset(new NotificationQueue<Func>());
616
617   // We allocate fnRunner_ separately, rather than declaring it directly
618   // as a member of EventBase solely so that we don't need to include
619   // NotificationQueue.h from EventBase.h
620   fnRunner_.reset(new FunctionRunner());
621
622   // Mark this as an internal event, so event_base_loop() will return if
623   // there are no other events besides this one installed.
624   //
625   // Most callers don't care about the internal notification queue used by
626   // EventBase.  The queue is always installed, so if we did count the queue as
627   // an active event, loop() would never exit with no more events to process.
628   // Users can use loopForever() if they do care about the notification queue.
629   // (This is useful for EventBase threads that do nothing but process
630   // runInEventBaseThread() notifications.)
631   fnRunner_->startConsumingInternal(this, queue_.get());
632 }
633
634 void EventBase::SmoothLoopTime::setTimeInterval(
635     std::chrono::microseconds timeInterval) {
636   expCoeff_ = -1.0 / timeInterval.count();
637   VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
638 }
639
640 void EventBase::SmoothLoopTime::reset(double value) {
641   value_ = value;
642 }
643
644 void EventBase::SmoothLoopTime::addSample(
645     std::chrono::microseconds idle,
646     std::chrono::microseconds busy) {
647   /*
648    * Position at which the busy sample is considered to be taken.
649    * (Allows to quickly skew our average without editing much code)
650    */
651   enum BusySamplePosition {
652     RIGHT = 0, // busy sample placed at the end of the iteration
653     CENTER = 1, // busy sample placed at the middle point of the iteration
654     LEFT = 2, // busy sample placed at the beginning of the iteration
655   };
656
657   // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
658   // and D676020 for more info on this calculation.
659   VLOG(11) << "idle " << idle.count() << " oldBusyLeftover_ "
660            << oldBusyLeftover_.count() << " idle + oldBusyLeftover_ "
661            << (idle + oldBusyLeftover_).count() << " busy " << busy.count()
662            << " " << __PRETTY_FUNCTION__;
663   idle += oldBusyLeftover_ + busy;
664   oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
665   idle -= oldBusyLeftover_;
666
667   double coeff = exp(idle.count() * expCoeff_);
668   value_ *= coeff;
669   value_ += (1.0 - coeff) * busy.count();
670 }
671
672 bool EventBase::nothingHandledYet() const noexcept {
673   VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
674   return (nextLoopCnt_ != latestLoopCnt_);
675 }
676
677 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
678                                       InternalEnum internal) {
679
680   struct event* ev = obj->getEvent();
681   assert(ev->ev_base == nullptr);
682
683   event_base_set(getLibeventBase(), ev);
684   if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
685     // Set the EVLIST_INTERNAL flag
686     event_ref_flags(ev) |= EVLIST_INTERNAL;
687   }
688 }
689
690 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
691   cancelTimeout(obj);
692   struct event* ev = obj->getEvent();
693   ev->ev_base = nullptr;
694 }
695
696 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
697                                  TimeoutManager::timeout_type timeout) {
698   assert(isInEventBaseThread());
699   // Set up the timeval and add the event
700   struct timeval tv;
701   tv.tv_sec = long(timeout.count() / 1000LL);
702   tv.tv_usec = long((timeout.count() % 1000LL) * 1000LL);
703
704   struct event* ev = obj->getEvent();
705   if (event_add(ev, &tv) < 0) {
706     LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
707     return false;
708   }
709
710   return true;
711 }
712
713 void EventBase::cancelTimeout(AsyncTimeout* obj) {
714   assert(isInEventBaseThread());
715   struct event* ev = obj->getEvent();
716   if (EventUtil::isEventRegistered(ev)) {
717     event_del(ev);
718   }
719 }
720
721 void EventBase::setName(const std::string& name) {
722   assert(isInEventBaseThread());
723   name_ = name;
724
725   if (isRunning()) {
726     setThreadName(loopThread_.load(std::memory_order_relaxed),
727                   name_);
728   }
729 }
730
731 const std::string& EventBase::getName() {
732   assert(isInEventBaseThread());
733   return name_;
734 }
735
736 const char* EventBase::getLibeventVersion() { return event_get_version(); }
737 const char* EventBase::getLibeventMethod() { return event_get_method(); }
738
739 } // folly