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