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