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