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