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