Don't use Pthread in EventBase
[folly.git] / folly / io / async / EventBase.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <atomic>
20 #include <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(std::chrono::microseconds 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(std::chrono::milliseconds 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) != std::thread::id();
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 == std::thread::id() || tid == std::this_thread::get_id();
488   }
489
490   bool inRunningEventBaseThread() const {
491     return loopThread_.load(std::memory_order_relaxed) ==
492         std::this_thread::get_id();
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(std::chrono::microseconds timeInterval)
523         : expCoeff_(-1.0 / timeInterval.count()),
524           value_(0.0),
525           oldBusyLeftover_(0) {
526       VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
527     }
528
529     void setTimeInterval(std::chrono::microseconds timeInterval);
530     void reset(double value = 0.0);
531
532     void addSample(
533         std::chrono::microseconds idle,
534         std::chrono::microseconds busy);
535
536     double get() const {
537       return value_;
538     }
539
540     void dampen(double factor) {
541       value_ *= factor;
542     }
543
544    private:
545     double expCoeff_;
546     double value_;
547     std::chrono::microseconds oldBusyLeftover_;
548   };
549
550   void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
551     assert(enableTimeMeasurement_);
552     observer_ = observer;
553   }
554
555   const std::shared_ptr<EventBaseObserver>& getObserver() {
556     return observer_;
557   }
558
559   /**
560    * Setup execution observation/instrumentation for every EventHandler
561    * executed in this EventBase.
562    *
563    * @param executionObserver   EventHandle's execution observer.
564    */
565   void setExecutionObserver(ExecutionObserver* observer) {
566     executionObserver_ = observer;
567   }
568
569   /**
570    * Gets the execution observer associated with this EventBase.
571    */
572   ExecutionObserver* getExecutionObserver() {
573     return executionObserver_;
574   }
575
576   /**
577    * Set the name of the thread that runs this event base.
578    */
579   void setName(const std::string& name);
580
581   /**
582    * Returns the name of the thread that runs this event base.
583    */
584   const std::string& getName();
585
586   /// Implements the Executor interface
587   void add(Cob fn) override {
588     // runInEventBaseThread() takes a const&,
589     // so no point in doing std::move here.
590     runInEventBaseThread(std::move(fn));
591   }
592
593   /// Implements the DrivableExecutor interface
594   void drive() override {
595     // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
596     // released inside a loop.
597     ++loopKeepAliveCount_;
598     SCOPE_EXIT {
599       --loopKeepAliveCount_;
600     };
601     loopOnce();
602   }
603
604   struct LoopKeepAliveDeleter {
605     void operator()(EventBase* evb) {
606       DCHECK(evb->isInEventBaseThread());
607       evb->loopKeepAliveCount_--;
608     }
609   };
610   using LoopKeepAlive = std::unique_ptr<EventBase, LoopKeepAliveDeleter>;
611
612   /// Returns you a handle which make loop() behave like loopForever() until
613   /// destroyed. loop() will return to its original behavior only when all
614   /// loop keep-alives are released. Loop holder is safe to release only from
615   /// EventBase thread.
616   ///
617   /// May return no op LoopKeepAlive if loopForever() is already running.
618   LoopKeepAlive loopKeepAlive() {
619     DCHECK(isInEventBaseThread());
620     loopKeepAliveCount_++;
621     return LoopKeepAlive(this);
622   }
623
624   // Thread-safe version of loopKeepAlive()
625   LoopKeepAlive loopKeepAliveAtomic() {
626     if (inRunningEventBaseThread()) {
627       return loopKeepAlive();
628     }
629     loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
630     return LoopKeepAlive(this);
631   }
632
633   // TimeoutManager
634   void attachTimeoutManager(
635       AsyncTimeout* obj,
636       TimeoutManager::InternalEnum internal) override final;
637
638   void detachTimeoutManager(AsyncTimeout* obj) override final;
639
640   bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
641       override final;
642
643   void cancelTimeout(AsyncTimeout* obj) override final;
644
645   bool isInTimeoutManagerThread() override final {
646     return isInEventBaseThread();
647   }
648
649  private:
650   void applyLoopKeepAlive();
651
652   ssize_t loopKeepAliveCount();
653
654   /*
655    * Helper function that tells us whether we have already handled
656    * some event/timeout/callback in this loop iteration.
657    */
658   bool nothingHandledYet() const noexcept;
659
660   typedef LoopCallback::List LoopCallbackList;
661   class FunctionRunner;
662
663   bool loopBody(int flags = 0);
664
665   // executes any callbacks queued by runInLoop(); returns false if none found
666   bool runLoopCallbacks();
667
668   void initNotificationQueue();
669
670   // should only be accessed through public getter
671   HHWheelTimer::UniquePtr wheelTimer_;
672
673   LoopCallbackList loopCallbacks_;
674   LoopCallbackList runBeforeLoopCallbacks_;
675   LoopCallbackList onDestructionCallbacks_;
676
677   // This will be null most of the time, but point to currentCallbacks
678   // if we are in the middle of running loop callbacks, such that
679   // runInLoop(..., true) will always run in the current loop
680   // iteration.
681   LoopCallbackList* runOnceCallbacks_;
682
683   // stop_ is set by terminateLoopSoon() and is used by the main loop
684   // to determine if it should exit
685   std::atomic<bool> stop_;
686
687   // The ID of the thread running the main loop.
688   // std::thread::id{} if loop is not running.
689   std::atomic<std::thread::id> loopThread_;
690
691   // pointer to underlying event_base class doing the heavy lifting
692   event_base* evb_;
693
694   // A notification queue for runInEventBaseThread() to use
695   // to send function requests to the EventBase thread.
696   std::unique_ptr<NotificationQueue<Func>> queue_;
697   std::unique_ptr<FunctionRunner> fnRunner_;
698   ssize_t loopKeepAliveCount_{0};
699   std::atomic<ssize_t> loopKeepAliveCountAtomic_{0};
700   bool loopKeepAliveActive_{false};
701
702   // limit for latency in microseconds (0 disables)
703   std::chrono::microseconds 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   // Wrap-around loop counter to detect beginning of each loop
722   uint64_t nextLoopCnt_;
723   uint64_t latestLoopCnt_;
724   std::chrono::steady_clock::time_point startWork_;
725   // Prevent undefined behavior from invoking event_base_loop() reentrantly.
726   // This is needed since many projects use libevent-1.4, which lacks commit
727   // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
728   // https://github.com/libevent/libevent/.
729   bool invokingLoop_{false};
730
731   // Observer to export counters
732   std::shared_ptr<EventBaseObserver> observer_;
733   uint32_t observerSampleCount_;
734
735   // EventHandler's execution observer.
736   ExecutionObserver* executionObserver_;
737
738   // Name of the thread running this EventBase
739   std::string name_;
740
741   // allow runOnDestruction() to be called from any threads
742   std::mutex onDestructionCallbacksMutex_;
743
744   // see EventBaseLocal
745   friend class detail::EventBaseLocalBase;
746   template <typename T> friend class EventBaseLocal;
747   std::mutex localStorageMutex_;
748   std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
749   std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
750 };
751
752 template <typename T>
753 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
754   return runInEventBaseThread([=] { fn(arg); });
755 }
756
757 template <typename T>
758 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
759   return runInEventBaseThreadAndWait([=] { fn(arg); });
760 }
761
762 template <typename T>
763 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
764     void (*fn)(T*),
765     T* arg) {
766   return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });
767 }
768
769 } // folly