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