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