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