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