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