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