Give each eventbase a wheeltimer
[folly.git] / folly / io / async / EventBase.h
1 /*
2  * Copyright 2016 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 #pragma once
18
19 #include <atomic>
20 #include <cstdlib>
21 #include <errno.h>
22 #include <functional>
23 #include <list>
24 #include <math.h>
25 #include <memory>
26 #include <mutex>
27 #include <queue>
28 #include <set>
29 #include <stack>
30 #include <unordered_map>
31 #include <unordered_set>
32 #include <utility>
33
34 #include <boost/intrusive/list.hpp>
35 #include <boost/utility.hpp>
36
37 #include <folly/Executor.h>
38 #include <folly/Function.h>
39 #include <folly/Portability.h>
40 #include <folly/experimental/ExecutionObserver.h>
41 #include <folly/futures/DrivableExecutor.h>
42 #include <folly/io/async/AsyncTimeout.h>
43 #include <folly/io/async/HHWheelTimer.h>
44 #include <folly/io/async/Request.h>
45 #include <folly/io/async/TimeoutManager.h>
46 #include <folly/portability/PThread.h>
47 #include <glog/logging.h>
48
49 #include <event.h>  // libevent
50
51 namespace folly {
52
53 typedef std::function<void()> Cob;
54 template <typename MessageT>
55 class NotificationQueue;
56
57 namespace detail {
58 class EventBaseLocalBase;
59
60 class EventBaseLocalBaseBase {
61  public:
62   virtual void onEventBaseDestruction(EventBase& evb) = 0;
63   virtual ~EventBaseLocalBaseBase() = default;
64 };
65 }
66 template <typename T>
67 class EventBaseLocal;
68
69 class EventBaseObserver {
70  public:
71   virtual ~EventBaseObserver() = default;
72
73   virtual uint32_t getSampleRate() const = 0;
74
75   virtual void loopSample(
76     int64_t busyTime, int64_t idleTime) = 0;
77 };
78
79 // Helper class that sets and retrieves the EventBase associated with a given
80 // request via RequestContext. See Request.h for that mechanism.
81 class RequestEventBase : public RequestData {
82  public:
83   static EventBase* get() {
84     auto data = dynamic_cast<RequestEventBase*>(
85         RequestContext::get()->getContextData(kContextDataName));
86     if (!data) {
87       return nullptr;
88     }
89     return data->eb_;
90   }
91
92   static void set(EventBase* eb) {
93     RequestContext::get()->setContextData(
94         kContextDataName,
95         std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
96   }
97
98  private:
99   explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
100   EventBase* eb_;
101   static constexpr const char* kContextDataName{"EventBase"};
102 };
103
104 /**
105  * This class is a wrapper for all asynchronous I/O processing functionality
106  *
107  * EventBase provides a main loop that notifies EventHandler callback objects
108  * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
109  * when a specified timeout has expired.  More complex, higher-level callback
110  * mechanisms can then be built on top of EventHandler and AsyncTimeout.
111  *
112  * A EventBase object can only drive an event loop for a single thread.  To
113  * take advantage of multiple CPU cores, most asynchronous I/O servers have one
114  * thread per CPU, and use a separate EventBase for each thread.
115  *
116  * In general, most EventBase methods may only be called from the thread
117  * running the EventBase's loop.  There are a few exceptions to this rule, for
118  * methods that are explicitly intended to allow communication with a
119  * EventBase from other threads.  When it is safe to call a method from
120  * another thread it is explicitly listed in the method comments.
121  */
122 class EventBase : private boost::noncopyable,
123                   public TimeoutManager,
124                   public DrivableExecutor {
125  public:
126   using Func = folly::Function<void()>;
127
128   /**
129    * A callback interface to use with runInLoop()
130    *
131    * Derive from this class if you need to delay some code execution until the
132    * next iteration of the event loop.  This allows you to schedule code to be
133    * invoked from the top-level of the loop, after your immediate callers have
134    * returned.
135    *
136    * If a LoopCallback object is destroyed while it is scheduled to be run in
137    * the next loop iteration, it will automatically be cancelled.
138    */
139   class LoopCallback {
140    public:
141     virtual ~LoopCallback() = default;
142
143     virtual void runLoopCallback() noexcept = 0;
144     void cancelLoopCallback() {
145       hook_.unlink();
146     }
147
148     bool isLoopCallbackScheduled() const {
149       return hook_.is_linked();
150     }
151
152    private:
153     typedef boost::intrusive::list_member_hook<
154       boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
155
156     ListHook hook_;
157
158     typedef boost::intrusive::list<
159       LoopCallback,
160       boost::intrusive::member_hook<LoopCallback, ListHook,
161                                     &LoopCallback::hook_>,
162       boost::intrusive::constant_time_size<false> > List;
163
164     // EventBase needs access to LoopCallbackList (and therefore to hook_)
165     friend class EventBase;
166     std::shared_ptr<RequestContext> context_;
167   };
168
169   /**
170    * Create a new EventBase object.
171    *
172    * @param enableTimeMeasurement Informs whether this event base should measure
173    *                              time. Disabling it would likely improve
174    *                              performance, but will disable some features
175    *                              that relies on time-measurement, including:
176    *                              observer, max latency and avg loop time.
177    */
178   explicit EventBase(bool enableTimeMeasurement = true);
179
180   /**
181    * Create a new EventBase object that will use the specified libevent
182    * event_base object to drive the event loop.
183    *
184    * The EventBase will take ownership of this event_base, and will call
185    * event_base_free(evb) when the EventBase is destroyed.
186    *
187    * @param enableTimeMeasurement Informs whether this event base should measure
188    *                              time. Disabling it would likely improve
189    *                              performance, but will disable some features
190    *                              that relies on time-measurement, including:
191    *                              observer, max latency and avg loop time.
192    */
193   explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
194   ~EventBase();
195
196   /**
197    * Runs the event loop.
198    *
199    * loop() will loop waiting for I/O or timeouts and invoking EventHandler
200    * and AsyncTimeout callbacks as their events become ready.  loop() will
201    * only return when there are no more events remaining to process, or after
202    * terminateLoopSoon() has been called.
203    *
204    * loop() may be called again to restart event processing after a previous
205    * call to loop() or loopForever() has returned.
206    *
207    * Returns true if the loop completed normally (if it processed all
208    * outstanding requests, or if terminateLoopSoon() was called).  If an error
209    * occurs waiting for events, false will be returned.
210    */
211   bool loop();
212
213   /**
214    * Wait for some events to become active, run them, then return.
215    *
216    * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
217    * are not any events to process.
218    *
219    * This is useful for callers that want to run the loop manually.
220    *
221    * Returns the same result as loop().
222    */
223   bool loopOnce(int flags = 0);
224
225   /**
226    * Runs the event loop.
227    *
228    * loopForever() behaves like loop(), except that it keeps running even if
229    * when there are no more user-supplied EventHandlers or AsyncTimeouts
230    * registered.  It will only return after terminateLoopSoon() has been
231    * called.
232    *
233    * This is useful for callers that want to wait for other threads to call
234    * runInEventBaseThread(), even when there are no other scheduled events.
235    *
236    * loopForever() may be called again to restart event processing after a
237    * previous call to loop() or loopForever() has returned.
238    *
239    * Throws a std::system_error if an error occurs.
240    */
241   void loopForever();
242
243   /**
244    * Causes the event loop to exit soon.
245    *
246    * This will cause an existing call to loop() or loopForever() to stop event
247    * processing and return, even if there are still events remaining to be
248    * processed.
249    *
250    * It is safe to call terminateLoopSoon() from another thread to cause loop()
251    * to wake up and return in the EventBase loop thread.  terminateLoopSoon()
252    * may also be called from the loop thread itself (for example, a
253    * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
254    * cause the loop to exit after the callback returns.)  If the loop is not
255    * running, this will cause the next call to loop to terminate soon after
256    * starting.  If a loop runs out of work (and so terminates on its own)
257    * concurrently with a call to terminateLoopSoon(), this may cause a race
258    * condition.
259    *
260    * Note that the caller is responsible for ensuring that cleanup of all event
261    * callbacks occurs properly.  Since terminateLoopSoon() causes the loop to
262    * exit even when there are pending events present, there may be remaining
263    * callbacks present waiting to be invoked.  If the loop is later restarted
264    * pending events will continue to be processed normally, however if the
265    * EventBase is destroyed after calling terminateLoopSoon() it is the
266    * caller's responsibility to ensure that cleanup happens properly even if
267    * some outstanding events are never processed.
268    */
269   void terminateLoopSoon();
270
271   /**
272    * Adds the given callback to a queue of things run after the current pass
273    * through the event loop completes.  Note that if this callback calls
274    * runInLoop() the new callback won't be called until the main event loop
275    * has gone through a cycle.
276    *
277    * This method may only be called from the EventBase's thread.  This
278    * essentially allows an event handler to schedule an additional callback to
279    * be invoked after it returns.
280    *
281    * Use runInEventBaseThread() to schedule functions from another thread.
282    *
283    * The thisIteration parameter makes this callback run in this loop
284    * iteration, instead of the next one, even if called from a
285    * runInLoop callback (normal io callbacks that call runInLoop will
286    * always run in this iteration).  This was originally added to
287    * support detachEventBase, as a user callback may have called
288    * terminateLoopSoon(), but we want to make sure we detach.  Also,
289    * detachEventBase almost always must be called from the base event
290    * loop to ensure the stack is unwound, since most users of
291    * EventBase are not thread safe.
292    *
293    * Ideally we would not need thisIteration, and instead just use
294    * runInLoop with loop() (instead of terminateLoopSoon).
295    */
296   void runInLoop(LoopCallback* callback, bool thisIteration = false);
297
298   /**
299    * Convenience function to call runInLoop() with a folly::Function.
300    *
301    * This creates a LoopCallback object to wrap the folly::Function, and invoke
302    * the folly::Function when the loop callback fires.  This is slightly more
303    * expensive than defining your own LoopCallback, but more convenient in
304    * areas that aren't too performance sensitive.
305    *
306    * This method may only be called from the EventBase's thread.  This
307    * essentially allows an event handler to schedule an additional callback to
308    * be invoked after it returns.
309    *
310    * Use runInEventBaseThread() to schedule functions from another thread.
311    */
312   void runInLoop(Func c, bool thisIteration = false);
313
314   /**
315    * Adds the given callback to a queue of things run before destruction
316    * of current EventBase.
317    *
318    * This allows users of EventBase that run in it, but don't control it,
319    * to be notified before EventBase gets destructed.
320    *
321    * Note: will be called from the thread that invoked EventBase destructor,
322    *       before the final run of loop callbacks.
323    */
324   void runOnDestruction(LoopCallback* callback);
325
326   /**
327    * Adds the given callback to a queue of things run after the notification
328    * queue is drained before the destruction of current EventBase.
329    *
330    * Note: will be called from the thread that invoked EventBase destructor,
331    *       after the final run of loop callbacks.
332    */
333   void runAfterDrain(Func cob);
334
335   /**
336    * Adds a callback that will run immediately *before* the event loop.
337    * This is very similar to runInLoop(), but will not cause the loop to break:
338    * For example, this callback could be used to get loop times.
339    */
340   void runBeforeLoop(LoopCallback* callback);
341
342   /**
343    * Run the specified function in the EventBase's thread.
344    *
345    * This method is thread-safe, and may be called from another thread.
346    *
347    * If runInEventBaseThread() is called when the EventBase loop is not
348    * running, the function call will be delayed until the next time the loop is
349    * started.
350    *
351    * If runInEventBaseThread() returns true the function has successfully been
352    * scheduled to run in the loop thread.  However, if the loop is terminated
353    * (and never later restarted) before it has a chance to run the requested
354    * function, the function will be run upon the EventBase's destruction.
355    *
356    * If two calls to runInEventBaseThread() are made from the same thread, the
357    * functions will always be run in the order that they were scheduled.
358    * Ordering between functions scheduled from separate threads is not
359    * guaranteed.
360    *
361    * @param fn  The function to run.  The function must not throw any
362    *     exceptions.
363    * @param arg An argument to pass to the function.
364    *
365    * @return Returns true if the function was successfully scheduled, or false
366    *         if there was an error scheduling the function.
367    */
368   template <typename T>
369   bool runInEventBaseThread(void (*fn)(T*), T* arg);
370
371   /**
372    * Run the specified function in the EventBase's thread
373    *
374    * This version of runInEventBaseThread() takes a folly::Function object.
375    * Note that this may be less efficient than the version that takes a plain
376    * function pointer and void* argument, if moving the function is expensive
377    * (e.g., if it wraps a lambda which captures some values with expensive move
378    * constructors).
379    *
380    * If the loop is terminated (and never later restarted) before it has a
381    * chance to run the requested function, the function will be run upon the
382    * EventBase's destruction.
383    *
384    * The function must not throw any exceptions.
385    */
386   bool runInEventBaseThread(Func fn);
387
388   /*
389    * Like runInEventBaseThread, but the caller waits for the callback to be
390    * executed.
391    */
392   template <typename T>
393   bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
394
395   /*
396    * Like runInEventBaseThread, but the caller waits for the callback to be
397    * executed.
398    */
399   bool runInEventBaseThreadAndWait(Func fn);
400
401   /*
402    * Like runInEventBaseThreadAndWait, except if the caller is already in the
403    * event base thread, the functor is simply run inline.
404    */
405   template <typename T>
406   bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
407
408   /*
409    * Like runInEventBaseThreadAndWait, except if the caller is already in the
410    * event base thread, the functor is simply run inline.
411    */
412   bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
413
414   /**
415    * Runs the given Cob at some time after the specified number of
416    * milliseconds.  (No guarantees exactly when.)
417    *
418    * Throws a std::system_error if an error occurs.
419    */
420   void runAfterDelay(
421       Func c,
422       uint32_t milliseconds,
423       TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
424
425   /**
426    * @see tryRunAfterDelay for more details
427    *
428    * @return  true iff the cob was successfully registered.
429    *
430    * */
431   bool tryRunAfterDelay(
432       Func cob,
433       uint32_t milliseconds,
434       TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
435
436   /**
437    * Set the maximum desired latency in us and provide a callback which will be
438    * called when that latency is exceeded.
439    * OBS: This functionality depends on time-measurement.
440    */
441   void setMaxLatency(int64_t maxLatency, Func maxLatencyCob) {
442     assert(enableTimeMeasurement_);
443     maxLatency_ = maxLatency;
444     maxLatencyCob_ = std::move(maxLatencyCob);
445   }
446
447
448   /**
449    * Set smoothing coefficient for loop load average; # of milliseconds
450    * for exp(-1) (1/2.71828...) decay.
451    */
452   void setLoadAvgMsec(uint32_t ms);
453
454   /**
455    * reset the load average to a desired value
456    */
457   void resetLoadAvg(double value = 0.0);
458
459   /**
460    * Get the average loop time in microseconds (an exponentially-smoothed ave)
461    */
462   double getAvgLoopTime() const {
463     assert(enableTimeMeasurement_);
464     return avgLoopTime_.get();
465   }
466
467   /**
468     * check if the event base loop is running.
469    */
470   bool isRunning() const {
471     return loopThread_.load(std::memory_order_relaxed) != 0;
472   }
473
474   /**
475    * wait until the event loop starts (after starting the event loop thread).
476    */
477   void waitUntilRunning();
478
479   int getNotificationQueueSize() const;
480
481   void setMaxReadAtOnce(uint32_t maxAtOnce);
482
483   /**
484    * Verify that current thread is the EventBase thread, if the EventBase is
485    * running.
486    */
487   bool isInEventBaseThread() const {
488     auto tid = loopThread_.load(std::memory_order_relaxed);
489     return tid == 0 || pthread_equal(tid, pthread_self());
490   }
491
492   bool inRunningEventBaseThread() const {
493     return pthread_equal(
494       loopThread_.load(std::memory_order_relaxed), pthread_self());
495   }
496
497   HHWheelTimer& timer() {
498     if (!wheelTimer_) {
499       wheelTimer_ = HHWheelTimer::newTimer(this, std::chrono::milliseconds(1));
500     }
501     return *wheelTimer_.get();
502   }
503
504   // --------- interface to underlying libevent base ------------
505   // Avoid using these functions if possible.  These functions are not
506   // guaranteed to always be present if we ever provide alternative EventBase
507   // implementations that do not use libevent internally.
508   event_base* getLibeventBase() const { return evb_; }
509   static const char* getLibeventVersion();
510   static const char* getLibeventMethod();
511
512   /**
513    * only EventHandler/AsyncTimeout subclasses and ourselves should
514    * ever call this.
515    *
516    * This is used to mark the beginning of a new loop cycle by the
517    * first handler fired within that cycle.
518    *
519    */
520   void bumpHandlingTime() override final;
521
522   class SmoothLoopTime {
523    public:
524     explicit SmoothLoopTime(uint64_t timeInterval)
525       : expCoeff_(-1.0/timeInterval)
526       , value_(0.0)
527       , oldBusyLeftover_(0) {
528       VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
529     }
530
531     void setTimeInterval(uint64_t timeInterval);
532     void reset(double value = 0.0);
533
534     void addSample(int64_t idle, int64_t busy);
535
536     double get() const {
537       return value_;
538     }
539
540     void dampen(double factor) {
541       value_ *= factor;
542     }
543
544    private:
545     double  expCoeff_;
546     double  value_;
547     int64_t oldBusyLeftover_;
548   };
549
550   void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
551     assert(enableTimeMeasurement_);
552     observer_ = observer;
553   }
554
555   const std::shared_ptr<EventBaseObserver>& getObserver() {
556     return observer_;
557   }
558
559   /**
560    * Setup execution observation/instrumentation for every EventHandler
561    * executed in this EventBase.
562    *
563    * @param executionObserver   EventHandle's execution observer.
564    */
565   void setExecutionObserver(ExecutionObserver* observer) {
566     executionObserver_ = observer;
567   }
568
569   /**
570    * Gets the execution observer associated with this EventBase.
571    */
572   ExecutionObserver* getExecutionObserver() {
573     return executionObserver_;
574   }
575
576   /**
577    * Set the name of the thread that runs this event base.
578    */
579   void setName(const std::string& name);
580
581   /**
582    * Returns the name of the thread that runs this event base.
583    */
584   const std::string& getName();
585
586   /// Implements the Executor interface
587   void add(Cob fn) override {
588     // runInEventBaseThread() takes a const&,
589     // so no point in doing std::move here.
590     runInEventBaseThread(std::move(fn));
591   }
592
593   /// Implements the DrivableExecutor interface
594   void drive() override {
595     loopOnce();
596   }
597
598   struct LoopKeepAliveDeleter {
599     void operator()(EventBase* evb) {
600       DCHECK(evb->isInEventBaseThread());
601       evb->loopKeepAliveCount_--;
602     }
603   };
604   using LoopKeepAlive = std::unique_ptr<EventBase, LoopKeepAliveDeleter>;
605
606   /// Returns you a handle which make loop() behave like loopForever() until
607   /// destroyed. loop() will return to its original behavior only when all
608   /// loop keep-alives are released. Loop holder is safe to release only from
609   /// EventBase thread.
610   ///
611   /// May return no op LoopKeepAlive if loopForever() is already running.
612   LoopKeepAlive loopKeepAlive() {
613     DCHECK(isInEventBaseThread());
614     loopKeepAliveCount_++;
615     return LoopKeepAlive(this);
616   }
617
618  private:
619   // TimeoutManager
620   void attachTimeoutManager(AsyncTimeout* obj,
621                             TimeoutManager::InternalEnum internal) override;
622
623   void detachTimeoutManager(AsyncTimeout* obj) override;
624
625   bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
626     override;
627
628   void cancelTimeout(AsyncTimeout* obj) override;
629
630   bool isInTimeoutManagerThread() override final {
631     return isInEventBaseThread();
632   }
633
634   void applyLoopKeepAlive();
635
636   /*
637    * Helper function that tells us whether we have already handled
638    * some event/timeout/callback in this loop iteration.
639    */
640   bool nothingHandledYet() const noexcept;
641
642   // small object used as a callback arg with enough info to execute the
643   // appropriate client-provided Cob
644   class CobTimeout : public AsyncTimeout {
645    public:
646     CobTimeout(EventBase* b, Func c, TimeoutManager::InternalEnum in)
647         : AsyncTimeout(b, in), cob_(std::move(c)) {}
648
649     virtual void timeoutExpired() noexcept;
650
651    private:
652     Func cob_;
653
654    public:
655     typedef boost::intrusive::list_member_hook<
656       boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
657
658     ListHook hook;
659
660     typedef boost::intrusive::list<
661       CobTimeout,
662       boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
663       boost::intrusive::constant_time_size<false> > List;
664   };
665
666   typedef LoopCallback::List LoopCallbackList;
667   class FunctionRunner;
668
669   bool loopBody(int flags = 0);
670
671   // executes any callbacks queued by runInLoop(); returns false if none found
672   bool runLoopCallbacks(bool setContext = true);
673
674   void initNotificationQueue();
675
676   // should only be accessed through public getter
677   HHWheelTimer::UniquePtr wheelTimer_;
678
679   CobTimeout::List pendingCobTimeouts_;
680
681   LoopCallbackList loopCallbacks_;
682   LoopCallbackList runBeforeLoopCallbacks_;
683   LoopCallbackList onDestructionCallbacks_;
684   LoopCallbackList runAfterDrainCallbacks_;
685
686   // This will be null most of the time, but point to currentCallbacks
687   // if we are in the middle of running loop callbacks, such that
688   // runInLoop(..., true) will always run in the current loop
689   // iteration.
690   LoopCallbackList* runOnceCallbacks_;
691
692   // stop_ is set by terminateLoopSoon() and is used by the main loop
693   // to determine if it should exit
694   std::atomic<bool> stop_;
695
696   // The ID of the thread running the main loop.
697   // 0 if loop is not running.
698   // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
699   // even that atomic<pthread_t> is valid), but that's how it is
700   // everywhere (at least on Linux, FreeBSD, and OSX).
701   std::atomic<pthread_t> loopThread_;
702
703   // pointer to underlying event_base class doing the heavy lifting
704   event_base* evb_;
705
706   // A notification queue for runInEventBaseThread() to use
707   // to send function requests to the EventBase thread.
708   std::unique_ptr<NotificationQueue<Func>> queue_;
709   std::unique_ptr<FunctionRunner> fnRunner_;
710   size_t loopKeepAliveCount_{0};
711   bool loopKeepAliveActive_{false};
712
713   // limit for latency in microseconds (0 disables)
714   int64_t maxLatency_;
715
716   // exponentially-smoothed average loop time for latency-limiting
717   SmoothLoopTime avgLoopTime_;
718
719   // smoothed loop time used to invoke latency callbacks; differs from
720   // avgLoopTime_ in that it's scaled down after triggering a callback
721   // to reduce spamminess
722   SmoothLoopTime maxLatencyLoopTime_;
723
724   // callback called when latency limit is exceeded
725   Func maxLatencyCob_;
726
727   // Enables/disables time measurements in loopBody(). if disabled, the
728   // following functionality that relies on time-measurement, will not
729   // be supported: avg loop time, observer and max latency.
730   const bool enableTimeMeasurement_;
731
732   // we'll wait this long before running deferred callbacks if the event
733   // loop is idle.
734   static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
735
736   // Wrap-around loop counter to detect beginning of each loop
737   uint64_t nextLoopCnt_;
738   uint64_t latestLoopCnt_;
739   uint64_t startWork_;
740   // Prevent undefined behavior from invoking event_base_loop() reentrantly.
741   // This is needed since many projects use libevent-1.4, which lacks commit
742   // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
743   // https://github.com/libevent/libevent/.
744   bool invokingLoop_{false};
745
746   // Observer to export counters
747   std::shared_ptr<EventBaseObserver> observer_;
748   uint32_t observerSampleCount_;
749
750   // EventHandler's execution observer.
751   ExecutionObserver* executionObserver_;
752
753   // Name of the thread running this EventBase
754   std::string name_;
755
756   // allow runOnDestruction() to be called from any threads
757   std::mutex onDestructionCallbacksMutex_;
758
759   // allow runAfterDrain() to be called from any threads
760   std::mutex runAfterDrainCallbacksMutex_;
761
762   // see EventBaseLocal
763   friend class detail::EventBaseLocalBase;
764   template <typename T> friend class EventBaseLocal;
765   std::mutex localStorageMutex_;
766   std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
767   std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
768 };
769
770 template <typename T>
771 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
772   return runInEventBaseThread([=] { fn(arg); });
773 }
774
775 template <typename T>
776 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
777   return runInEventBaseThreadAndWait([=] { fn(arg); });
778 }
779
780 template <typename T>
781 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
782     void (*fn)(T*),
783     T* arg) {
784   return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });
785 }
786
787 } // folly