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