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