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