proxygen
folly::EventBase Class Reference

#include <EventBase.h>

Inheritance diagram for folly::EventBase:
folly::TimeoutManager folly::DrivableExecutor folly::IOExecutor folly::SequencedExecutor folly::ScheduledExecutor folly::Executor folly::Executor folly::Executor folly::Executor

Classes

class  FunctionLoopCallback
 
class  FunctionRunner
 
class  LoopCallback
 
class  SmoothLoopTime
 
class  StackFunctionLoopCallback
 

Public Types

using Func = folly::Function< void()>
 
- Public Types inherited from folly::TimeoutManager
enum  InternalEnum { InternalEnum::INTERNAL, InternalEnum::NORMAL }
 
typedef std::chrono::milliseconds timeout_type
 
using Func = folly::Function< void()>
 
- Public Types inherited from folly::ScheduledExecutor
typedef std::chrono::microseconds Duration
 
typedef std::chrono::steady_clock::time_point TimePoint
 

Public Member Functions

 EventBase ()
 
 EventBase (bool enableTimeMeasurement)
 
 EventBase (event_base *evb, bool enableTimeMeasurement=true)
 
 ~EventBase () override
 
bool loop ()
 
bool loopIgnoreKeepAlive ()
 
bool loopOnce (int flags=0)
 
void loopForever ()
 
void terminateLoopSoon ()
 
void runInLoop (LoopCallback *callback, bool thisIteration=false)
 
void runInLoop (Func c, bool thisIteration=false)
 
void runOnDestruction (LoopCallback *callback)
 
void runBeforeLoop (LoopCallback *callback)
 
template<typename T >
bool runInEventBaseThread (void(*fn)(T *), T *arg)
 
bool runInEventBaseThread (Func fn)
 
template<typename T >
bool runInEventBaseThreadAndWait (void(*fn)(T *), T *arg)
 
bool runInEventBaseThreadAndWait (Func fn)
 
template<typename T >
bool runImmediatelyOrRunInEventBaseThreadAndWait (void(*fn)(T *), T *arg)
 
bool runImmediatelyOrRunInEventBaseThreadAndWait (Func fn)
 
void setMaxLatency (std::chrono::microseconds maxLatency, Func maxLatencyCob)
 
void setLoadAvgMsec (std::chrono::milliseconds ms)
 
void resetLoadAvg (double value=0.0)
 
double getAvgLoopTime () const
 
bool isRunning () const
 
void waitUntilRunning ()
 
size_t getNotificationQueueSize () const
 
void setMaxReadAtOnce (uint32_t maxAtOnce)
 
bool isInEventBaseThread () const
 
bool inRunningEventBaseThread () const
 
void checkIsInEventBaseThread () const
 
void dcheckIsInEventBaseThread () const
 
HHWheelTimertimer ()
 
event_base * getLibeventBase () const
 
void bumpHandlingTime () final
 
void setObserver (const std::shared_ptr< EventBaseObserver > &observer)
 
const std::shared_ptr< EventBaseObserver > & getObserver ()
 
void setExecutionObserver (ExecutionObserver *observer)
 
ExecutionObservergetExecutionObserver ()
 
void setName (const std::string &name)
 
const std::stringgetName ()
 
void add (Cob fn) override
 Implements the Executor interface. More...
 
void drive () override
 Implements the DrivableExecutor interface. More...
 
void scheduleAt (Func &&fn, TimePoint const &timeout) override
 
void attachTimeoutManager (AsyncTimeout *obj, TimeoutManager::InternalEnum internal) final
 
void detachTimeoutManager (AsyncTimeout *obj) final
 
bool scheduleTimeout (AsyncTimeout *obj, TimeoutManager::timeout_type timeout) final
 
void cancelTimeout (AsyncTimeout *obj) final
 
bool isInTimeoutManagerThread () final
 
folly::VirtualEventBasegetVirtualEventBase ()
 
EventBasegetEventBase () override
 Implements the IOExecutor interface. More...
 
- Public Member Functions inherited from folly::TimeoutManager
 TimeoutManager ()
 
virtual ~TimeoutManager ()
 
void runAfterDelay (Func cob, uint32_t milliseconds, InternalEnum internal=InternalEnum::NORMAL)
 
bool tryRunAfterDelay (Func cob, uint32_t milliseconds, InternalEnum internal=InternalEnum::NORMAL)
 
- Public Member Functions inherited from folly::DrivableExecutor
 ~DrivableExecutor () override=default
 
- Public Member Functions inherited from folly::Executor
virtual ~Executor ()
 
virtual void addWithPriority (Func, int8_t priority)
 
virtual uint8_t getNumPriorities () const
 
- Public Member Functions inherited from folly::IOExecutor
 ~IOExecutor () override=default
 
- Public Member Functions inherited from folly::ScheduledExecutor
 ~ScheduledExecutor () override=default
 
void schedule (Func &&a)
 Alias for add() (for Rx consistency) More...
 
void schedule (Func &&a, Duration const &dur)
 
virtual TimePoint now ()
 Get this executor's notion of time. Must be threadsafe. More...
 

Static Public Member Functions

static const char * getLibeventVersion ()
 
static const char * getLibeventMethod ()
 
- Static Public Member Functions inherited from folly::Executor
template<typename ExecutorT >
static KeepAlive< ExecutorT > getKeepAliveToken (ExecutorT *executor)
 
template<typename ExecutorT >
static KeepAlive< ExecutorT > getKeepAliveToken (ExecutorT &executor)
 

Protected Member Functions

bool keepAliveAcquire () override
 
void keepAliveRelease () override
 
- Protected Member Functions inherited from folly::TimeoutManager
void clearCobTimeouts ()
 

Private Types

typedef LoopCallback::List LoopCallbackList
 

Private Member Functions

void applyLoopKeepAlive ()
 
ssize_t loopKeepAliveCount ()
 
bool nothingHandledYet () const noexcept
 
bool loopBody (int flags=0, bool ignoreKeepAlive=false)
 
bool runLoopCallbacks ()
 
void initNotificationQueue ()
 

Private Attributes

HHWheelTimer::UniquePtr wheelTimer_
 
LoopCallbackList loopCallbacks_
 
LoopCallbackList runBeforeLoopCallbacks_
 
LoopCallbackList onDestructionCallbacks_
 
LoopCallbackListrunOnceCallbacks_
 
std::atomic< bool > stop_
 
std::atomic< std::thread::id > loopThread_
 
event_base * evb_
 
std::unique_ptr< NotificationQueue< Func > > queue_
 
std::unique_ptr< FunctionRunnerfnRunner_
 
ssize_t loopKeepAliveCount_ {0}
 
std::atomic< ssize_t > loopKeepAliveCountAtomic_ {0}
 
bool loopKeepAliveActive_ {false}
 
std::chrono::microseconds maxLatency_
 
SmoothLoopTime avgLoopTime_
 
SmoothLoopTime maxLatencyLoopTime_
 
Func maxLatencyCob_
 
const bool enableTimeMeasurement_
 
std::size_t nextLoopCnt_
 
std::size_t latestLoopCnt_
 
std::chrono::steady_clock::time_point startWork_
 
bool invokingLoop_ {false}
 
std::shared_ptr< EventBaseObserverobserver_
 
uint32_t observerSampleCount_
 
ExecutionObserverexecutionObserver_
 
std::string name_
 
std::mutex onDestructionCallbacksMutex_
 
std::unordered_map< std::size_t, std::shared_ptr< void > > localStorage_
 
std::unordered_set< detail::EventBaseLocalBaseBase * > localStorageToDtor_
 
folly::once_flag virtualEventBaseInitFlag_
 
std::unique_ptr< VirtualEventBasevirtualEventBase_
 

Friends

class detail::EventBaseLocalBase
 
template<typename T >
class EventBaseLocal
 

Additional Inherited Members

- Static Public Attributes inherited from folly::Executor
static const int8_t LO_PRI = SCHAR_MIN
 
static const int8_t MID_PRI = 0
 
static const int8_t HI_PRI = SCHAR_MAX
 
- Static Protected Member Functions inherited from folly::Executor
template<typename ExecutorT >
static bool isKeepAliveDummy (const KeepAlive< ExecutorT > &keepAlive)
 
template<typename ExecutorT >
static KeepAlive< ExecutorT > makeKeepAlive (ExecutorT *executor)
 

Detailed Description

This class is a wrapper for all asynchronous I/O processing functionality

EventBase provides a main loop that notifies EventHandler callback objects when I/O is ready on a file descriptor, and notifies AsyncTimeout objects when a specified timeout has expired. More complex, higher-level callback mechanisms can then be built on top of EventHandler and AsyncTimeout.

A EventBase object can only drive an event loop for a single thread. To take advantage of multiple CPU cores, most asynchronous I/O servers have one thread per CPU, and use a separate EventBase for each thread.

In general, most EventBase methods may only be called from the thread running the EventBase's loop. There are a few exceptions to this rule, for methods that are explicitly intended to allow communication with a EventBase from other threads. When it is safe to call a method from another thread it is explicitly listed in the method comments.

Definition at line 128 of file EventBase.h.

Member Typedef Documentation

Definition at line 135 of file EventBase.h.

Definition at line 698 of file EventBase.h.

Constructor & Destructor Documentation

folly::EventBase::EventBase ( )
inline

Create a new EventBase object.

Same as EventBase(true), which constructs an EventBase that measures time.

Definition at line 210 of file EventBase.h.

References c, loop(), and folly::T.

210 : EventBase(true) {}
folly::EventBase::EventBase ( bool  enableTimeMeasurement)
explicit

Create a new EventBase object.

Parameters
enableTimeMeasurementInforms whether this event base should measure time. Disabling it would likely improve performance, but will disable some features that relies on time-measurement, including: observer, max latency and avg loop time.

Definition at line 76 of file EventBase.cpp.

References evb_, initNotificationQueue(), folly::lock(), folly::throwSystemError(), and UNLIKELY.

77  : runOnceCallbacks_(nullptr),
78  stop_(false),
79  loopThread_(),
80  queue_(nullptr),
81  fnRunner_(nullptr),
82  maxLatency_(0),
83  avgLoopTime_(std::chrono::seconds(2)),
85  enableTimeMeasurement_(enableTimeMeasurement),
87  std::size_t(-40)) // Early wrap-around so bugs will manifest soon
88  ,
90  startWork_(),
91  observer_(nullptr),
93  executionObserver_(nullptr) {
94  struct event ev;
95  {
96  std::lock_guard<std::mutex> lock(libevent_mutex_);
97 
98  // The value 'current_base' (libevent 1) or
99  // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
100  // allowing examination of its value without an explicit reference here.
101  // If ev.ev_base is nullptr, then event_init() must be called, otherwise
102  // call event_base_new().
103  event_set(&ev, 0, 0, nullptr, nullptr);
104  if (!ev.ev_base) {
105  evb_ = event_init();
106  }
107  }
108 
109  if (ev.ev_base) {
110  evb_ = event_base_new();
111  }
112 
113  if (UNLIKELY(evb_ == nullptr)) {
114  LOG(ERROR) << "EventBase(): Failed to init event base.";
115  folly::throwSystemError("error in EventBase::EventBase()");
116  }
117  VLOG(5) << "EventBase(): Created.";
119 }
std::chrono::microseconds maxLatency_
Definition: EventBase.h:741
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
LoopCallbackList * runOnceCallbacks_
Definition: EventBase.h:719
static std::mutex libevent_mutex_
Definition: EventBase.cpp:70
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
std::shared_ptr< EventBaseObserver > observer_
Definition: EventBase.h:770
auto lock(Synchronized< D, M > &synchronized, Args &&...args)
event_base * evb_
Definition: EventBase.h:730
std::chrono::steady_clock::time_point startWork_
Definition: EventBase.h:762
SmoothLoopTime maxLatencyLoopTime_
Definition: EventBase.h:749
std::atomic< bool > stop_
Definition: EventBase.h:723
ExecutionObserver * executionObserver_
Definition: EventBase.h:774
const bool enableTimeMeasurement_
Definition: EventBase.h:757
std::size_t nextLoopCnt_
Definition: EventBase.h:760
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735
std::size_t latestLoopCnt_
Definition: EventBase.h:761
void throwSystemError(Args &&...args)
Definition: Exception.h:76
#define UNLIKELY(x)
Definition: Likely.h:48
SmoothLoopTime avgLoopTime_
Definition: EventBase.h:744
uint32_t observerSampleCount_
Definition: EventBase.h:771
void initNotificationQueue()
Definition: EventBase.cpp:640
folly::EventBase::EventBase ( event_base *  evb,
bool  enableTimeMeasurement = true 
)
explicit

Create a new EventBase object that will use the specified libevent event_base object to drive the event loop.

The EventBase will take ownership of this event_base, and will call event_base_free(evb) when the EventBase is destroyed.

Parameters
enableTimeMeasurementInforms whether this event base should measure time. Disabling it would likely improve performance, but will disable some features that relies on time-measurement, including: observer, max latency and avg loop time.

Definition at line 122 of file EventBase.cpp.

References evb_, initNotificationQueue(), and UNLIKELY.

123  : runOnceCallbacks_(nullptr),
124  stop_(false),
125  loopThread_(),
126  evb_(evb),
127  queue_(nullptr),
128  fnRunner_(nullptr),
129  maxLatency_(0),
130  avgLoopTime_(std::chrono::seconds(2)),
132  enableTimeMeasurement_(enableTimeMeasurement),
133  nextLoopCnt_(
134  std::size_t(-40)) // Early wrap-around so bugs will manifest soon
135  ,
137  startWork_(),
138  observer_(nullptr),
140  executionObserver_(nullptr) {
141  if (UNLIKELY(evb_ == nullptr)) {
142  LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
143  throw std::invalid_argument("EventBase(): event base cannot be nullptr");
144  }
146 }
std::chrono::microseconds maxLatency_
Definition: EventBase.h:741
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
LoopCallbackList * runOnceCallbacks_
Definition: EventBase.h:719
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
std::shared_ptr< EventBaseObserver > observer_
Definition: EventBase.h:770
event_base * evb_
Definition: EventBase.h:730
std::chrono::steady_clock::time_point startWork_
Definition: EventBase.h:762
SmoothLoopTime maxLatencyLoopTime_
Definition: EventBase.h:749
std::atomic< bool > stop_
Definition: EventBase.h:723
ExecutionObserver * executionObserver_
Definition: EventBase.h:774
const bool enableTimeMeasurement_
Definition: EventBase.h:757
std::size_t nextLoopCnt_
Definition: EventBase.h:760
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735
std::size_t latestLoopCnt_
Definition: EventBase.h:761
#define UNLIKELY(x)
Definition: Likely.h:48
SmoothLoopTime avgLoopTime_
Definition: EventBase.h:744
uint32_t observerSampleCount_
Definition: EventBase.h:771
void initNotificationQueue()
Definition: EventBase.cpp:640
folly::EventBase::~EventBase ( )
override

Definition at line 148 of file EventBase.cpp.

References applyLoopKeepAlive(), folly::TimeoutManager::clearCobTimeouts(), evb_, fnRunner_, localStorageToDtor_, folly::lock(), loopKeepAliveCount(), loopOnce(), onDestructionCallbacks_, runBeforeLoopCallbacks_, folly::EventBase::LoopCallback::runLoopCallback(), runLoopCallbacks(), and virtualEventBase_.

Referenced by folly::run().

148  {
149  std::future<void> virtualEventBaseDestroyFuture;
150  if (virtualEventBase_) {
151  virtualEventBaseDestroyFuture = virtualEventBase_->destroy();
152  }
153 
154  // Keep looping until all keep-alive handles are released. Each keep-alive
155  // handle signals that some external code will still schedule some work on
156  // this EventBase (so it's not safe to destroy it).
157  while (loopKeepAliveCount() > 0) {
159  loopOnce();
160  }
161 
162  if (virtualEventBaseDestroyFuture.valid()) {
163  virtualEventBaseDestroyFuture.get();
164  }
165 
166  // Call all destruction callbacks, before we start cleaning up our state.
167  while (!onDestructionCallbacks_.empty()) {
168  LoopCallback* callback = &onDestructionCallbacks_.front();
169  onDestructionCallbacks_.pop_front();
170  callback->runLoopCallback();
171  }
172 
174 
175  DCHECK_EQ(0u, runBeforeLoopCallbacks_.size());
176 
177  (void)runLoopCallbacks();
178 
179  if (!fnRunner_->consumeUntilDrained()) {
180  LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
181  }
182 
183  // Stop consumer before deleting NotificationQueue
184  fnRunner_->stopConsuming();
185  {
186  std::lock_guard<std::mutex> lock(libevent_mutex_);
187  event_base_free(evb_);
188  }
189 
190  for (auto storage : localStorageToDtor_) {
191  storage->onEventBaseDestruction(*this);
192  }
193 
194  VLOG(5) << "EventBase(): Destroyed.";
195 }
LoopCallbackList runBeforeLoopCallbacks_
Definition: EventBase.h:712
LoopCallbackList onDestructionCallbacks_
Definition: EventBase.h:713
static std::mutex libevent_mutex_
Definition: EventBase.cpp:70
bool runLoopCallbacks()
Definition: EventBase.cpp:612
void applyLoopKeepAlive()
Definition: EventBase.cpp:433
std::unordered_set< detail::EventBaseLocalBaseBase * > localStorageToDtor_
Definition: EventBase.h:787
ssize_t loopKeepAliveCount()
Definition: EventBase.cpp:423
bool loopOnce(int flags=0)
Definition: EventBase.cpp:271
std::unique_ptr< VirtualEventBase > virtualEventBase_
Definition: EventBase.h:790
auto lock(Synchronized< D, M > &synchronized, Args &&...args)
event_base * evb_
Definition: EventBase.h:730
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735

Member Function Documentation

void folly::EventBase::add ( Cob  fn)
inlineoverridevirtual

Implements the Executor interface.

Implements folly::ScheduledExecutor.

Definition at line 624 of file EventBase.h.

References folly::gen::move.

Referenced by folly::ScopedEventBaseThread::add().

624  {
625  // runInEventBaseThread() takes a const&,
626  // so no point in doing std::move here.
628  }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool runInEventBaseThread(void(*fn)(T *), T *arg)
Definition: EventBase.h:794
void folly::EventBase::applyLoopKeepAlive ( )
private

Definition at line 433 of file EventBase.cpp.

References fnRunner_, loopKeepAliveActive_, loopKeepAliveCount(), queue_, and virtualEventBase_.

Referenced by loopBody(), loopForever(), and ~EventBase().

433  {
434  auto keepAliveCount = loopKeepAliveCount();
435  // Make sure default VirtualEventBase won't hold EventBase::loop() forever.
436  if (virtualEventBase_ && virtualEventBase_->keepAliveCount() == 1) {
437  --keepAliveCount;
438  }
439 
440  if (loopKeepAliveActive_ && keepAliveCount == 0) {
441  // Restore the notification queue internal flag
442  fnRunner_->stopConsuming();
443  fnRunner_->startConsumingInternal(this, queue_.get());
444  loopKeepAliveActive_ = false;
445  } else if (!loopKeepAliveActive_ && keepAliveCount > 0) {
446  // Update the notification queue event to treat it as a normal
447  // (non-internal) event. The notification queue event always remains
448  // installed, and the main loop won't exit with it installed.
449  fnRunner_->stopConsuming();
450  fnRunner_->startConsuming(this, queue_.get());
451  loopKeepAliveActive_ = true;
452  }
453 }
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
ssize_t loopKeepAliveCount()
Definition: EventBase.cpp:423
std::unique_ptr< VirtualEventBase > virtualEventBase_
Definition: EventBase.h:790
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735
bool loopKeepAliveActive_
Definition: EventBase.h:738
void folly::EventBase::attachTimeoutManager ( AsyncTimeout obj,
TimeoutManager::InternalEnum  internal 
)
finalvirtual

Attaches/detaches TimeoutManager to AsyncTimeout

Implements folly::TimeoutManager.

Definition at line 694 of file EventBase.cpp.

References folly::event_ref_flags(), folly::AsyncTimeout::getEvent(), getLibeventBase(), and folly::TimeoutManager::INTERNAL.

694  {
695  struct event* ev = obj->getEvent();
696  assert(ev->ev_base == nullptr);
697 
698  event_base_set(getLibeventBase(), ev);
699  if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
700  // Set the EVLIST_INTERNAL flag
701  event_ref_flags(ev) |= EVLIST_INTERNAL;
702  }
703 }
auto event_ref_flags(struct event *ev) -> decltype(std::ref(ev->ev_flags))
Definition: EventUtil.h:41
event_base * getLibeventBase() const
Definition: EventBase.h:537
void folly::EventBase::bumpHandlingTime ( )
finalvirtual

only EventHandler/AsyncTimeout subclasses and ourselves should ever call this.

This is used to mark the beginning of a new loop cycle by the first handler fired within that cycle.

Implements folly::TimeoutManager.

Definition at line 476 of file EventBase.cpp.

References enableTimeMeasurement_, latestLoopCnt_, nextLoopCnt_, nothingHandledYet(), now(), and startWork_.

Referenced by folly::EventHandler::libeventCallback(), and runLoopCallbacks().

476  {
477  if (!enableTimeMeasurement_) {
478  return;
479  }
480 
481  VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
482  << " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
483  if (nothingHandledYet()) {
485  // set the time
487 
488  VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
489  << " (loop) startWork_ " << startWork_.time_since_epoch().count();
490  }
491 }
std::chrono::steady_clock::time_point now()
std::chrono::steady_clock::time_point startWork_
Definition: EventBase.h:762
const bool enableTimeMeasurement_
Definition: EventBase.h:757
std::size_t nextLoopCnt_
Definition: EventBase.h:760
std::size_t latestLoopCnt_
Definition: EventBase.h:761
bool nothingHandledYet() const noexcept
Definition: EventBase.cpp:689
void folly::EventBase::cancelTimeout ( AsyncTimeout obj)
finalvirtual

Cancels the AsyncTimeout, if scheduled

Implements folly::TimeoutManager.

Definition at line 732 of file EventBase.cpp.

References dcheckIsInEventBaseThread(), folly::AsyncTimeout::getEvent(), and folly::EventUtil::isEventRegistered().

Referenced by detachTimeoutManager().

732  {
734  struct event* ev = obj->getEvent();
736  event_del(ev);
737  }
738 }
static bool isEventRegistered(const struct event *ev)
Definition: EventUtil.h:51
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
void folly::EventBase::checkIsInEventBaseThread ( ) const

Equivalent to CHECK(isInEventBaseThread()) (and assert/DCHECK for dcheckIsInEventBaseThread), but it prints more information on failure.

Definition at line 205 of file EventBase.cpp.

References folly::getThreadName(), loopThread_, and folly::Optional< Value >::value_or().

205  {
206  auto evbTid = loopThread_.load(std::memory_order_relaxed);
207  if (evbTid == std::thread::id()) {
208  return;
209  }
210 
211  // Using getThreadName(evbTid) instead of name_ will work also if
212  // the thread name is set outside of EventBase (and name_ is empty).
213  auto curTid = std::this_thread::get_id();
214  CHECK(evbTid == curTid)
215  << "This logic must be executed in the event base thread. "
216  << "Event base thread name: \""
217  << folly::getThreadName(evbTid).value_or("")
218  << "\", current thread name: \""
219  << folly::getThreadName(curTid).value_or("") << "\"";
220 }
Optional< std::string > getThreadName(std::thread::id id)
Definition: ThreadName.cpp:90
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
FOLLY_CPP14_CONSTEXPR Value value_or(U &&dflt) const &
Definition: Optional.h:330
void folly::EventBase::dcheckIsInEventBaseThread ( ) const
inline

Definition at line 520 of file EventBase.h.

References folly::kIsDebug.

Referenced by folly::AsyncServerSocket::addAcceptCallback(), folly::AsyncUDPSocket::AsyncUDPSocket(), folly::EventHandler::attachEventBase(), folly::AsyncServerSocket::attachEventBase(), folly::AsyncSocket::attachEventBase(), folly::AsyncServerSocket::backoffTimeoutExpired(), folly::AsyncServerSocket::bind(), cancelTimeout(), folly::AsyncUDPSocket::close(), folly::AsyncSocket::close(), folly::AsyncSocket::closeNow(), folly::AsyncSocket::connect(), folly::AsyncServerSocket::detachEventBase(), folly::AsyncSocket::detachEventBase(), wangle::EvbHandshakeHelper::dropConnection(), folly::detail::EventBaseLocalBase::erase(), getName(), folly::AsyncServerSocket::getNumPendingMessagesInQueue(), folly::detail::EventBaseLocalBase::getVoid(), folly::NotificationQueue< MessageT >::Consumer::init(), folly::AsyncSocket::init(), folly::AsyncSocket::ioReady(), folly::AsyncSocket::isDetachable(), folly::AsyncSocket::isZeroCopyWriteInProgress(), folly::AsyncServerSocket::listen(), folly::detail::EventBaseLocalBase::onEventBaseDestruction(), folly::AsyncServerSocket::pauseAccepting(), folly::AsyncSocket::processZeroCopyWriteInProgress(), folly::AsyncServerSocket::removeAcceptCallback(), runBeforeLoop(), runInLoop(), scheduleTimeout(), folly::AsyncSocket::setErrMessageCB(), setName(), folly::AsyncSocket::setReadCB(), folly::AsyncSocket::setSendTimeout(), folly::detail::EventBaseLocalBase::setVoid(), folly::AsyncSocket::shutdownWrite(), folly::AsyncSocket::shutdownWriteNow(), folly::AsyncSSLSocket::sslAccept(), folly::AsyncSSLSocket::sslConn(), folly::AsyncServerSocket::startAccepting(), folly::AsyncServerSocket::stopAccepting(), folly::AsyncSocket::timeoutExpired(), folly::AsyncSocket::updateEventRegistration(), folly::AsyncServerSocket::useExistingSockets(), and folly::AsyncSocket::writeImpl().

520  {
521  if (kIsDebug) {
523  }
524  }
constexpr auto kIsDebug
Definition: Portability.h:264
void checkIsInEventBaseThread() const
Definition: EventBase.cpp:205
void folly::EventBase::detachTimeoutManager ( AsyncTimeout obj)
finalvirtual

Implements folly::TimeoutManager.

Definition at line 705 of file EventBase.cpp.

References cancelTimeout(), and folly::AsyncTimeout::getEvent().

705  {
706  cancelTimeout(obj);
707  struct event* ev = obj->getEvent();
708  ev->ev_base = nullptr;
709 }
void cancelTimeout(AsyncTimeout *obj) final
Definition: EventBase.cpp:732
void folly::EventBase::drive ( )
inlineoverridevirtual

Implements the DrivableExecutor interface.

Implements folly::DrivableExecutor.

Definition at line 631 of file EventBase.h.

References SCOPE_EXIT, and folly::detail::timeout.

Referenced by TEST().

631  {
633  SCOPE_EXIT {
635  };
636  loopOnce();
637  }
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
bool loopOnce(int flags=0)
Definition: EventBase.cpp:271
ssize_t loopKeepAliveCount_
Definition: EventBase.h:736
double folly::EventBase::getAvgLoopTime ( ) const
inline

Get the average loop time in microseconds (an exponentially-smoothed ave)

Definition at line 479 of file EventBase.h.

Referenced by TEST().

479  {
480  assert(enableTimeMeasurement_);
481  return avgLoopTime_.get();
482  }
const bool enableTimeMeasurement_
Definition: EventBase.h:757
SmoothLoopTime avgLoopTime_
Definition: EventBase.h:744
EventBase * folly::EventBase::getEventBase ( )
overridevirtual

Implements the IOExecutor interface.

Implements folly::IOExecutor.

Definition at line 776 of file EventBase.cpp.

References folly::EventBase::SmoothLoopTime::buffer_interval_.

Referenced by AcceptRoutingHandlerTest::getEventBase(), proxygen::PassThroughTransportFilter::getEventBase(), and TEST().

776  {
777  return this;
778 }
ExecutionObserver* folly::EventBase::getExecutionObserver ( )
inline

Gets the execution observer associated with this EventBase.

Definition at line 609 of file EventBase.h.

References name, and string.

Referenced by folly::EventHandler::libeventCallback().

609  {
610  return executionObserver_;
611  }
ExecutionObserver * executionObserver_
Definition: EventBase.h:774
event_base* folly::EventBase::getLibeventBase ( ) const
inline

Definition at line 537 of file EventBase.h.

References evb_.

Referenced by attachTimeoutManager(), folly::AsyncSignalHandler::registerSignalHandler(), and folly::EventHandler::setEventBase().

537  {
538  return evb_;
539  }
event_base * evb_
Definition: EventBase.h:730
const char * folly::EventBase::getLibeventMethod ( )
static

Definition at line 764 of file EventBase.cpp.

764  {
765  return event_get_method();
766 }
const char * folly::EventBase::getLibeventVersion ( )
static

Definition at line 761 of file EventBase.cpp.

761  {
762  return event_get_version();
763 }
const std::string & folly::EventBase::getName ( )

Returns the name of the thread that runs this event base.

Definition at line 749 of file EventBase.cpp.

References dcheckIsInEventBaseThread(), and name_.

749  {
751  return name_;
752 }
std::string name_
Definition: EventBase.h:777
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
size_t folly::EventBase::getNotificationQueueSize ( ) const

Definition at line 197 of file EventBase.cpp.

References queue_.

Referenced by loopBody().

197  {
198  return queue_->size();
199 }
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
const std::shared_ptr<EventBaseObserver>& folly::EventBase::getObserver ( )
inline

Definition at line 592 of file EventBase.h.

592  {
593  return observer_;
594  }
std::shared_ptr< EventBaseObserver > observer_
Definition: EventBase.h:770
VirtualEventBase & folly::EventBase::getVirtualEventBase ( )

Definition at line 768 of file EventBase.cpp.

References folly::call_once(), virtualEventBase_, and virtualEventBaseInitFlag_.

Referenced by folly::fibers::EventBaseLoopController::attachEventBase(), and TEST().

768  {
770  virtualEventBase_ = std::make_unique<VirtualEventBase>(*this);
771  });
772 
773  return *virtualEventBase_;
774 }
FOLLY_ALWAYS_INLINE void call_once(basic_once_flag< Mutex, Atom > &flag, F &&f, Args &&...args)
Definition: CallOnce.h:56
std::unique_ptr< VirtualEventBase > virtualEventBase_
Definition: EventBase.h:790
folly::once_flag virtualEventBaseInitFlag_
Definition: EventBase.h:789
void folly::EventBase::initNotificationQueue ( )
private

Definition at line 640 of file EventBase.cpp.

References fnRunner_, and queue_.

Referenced by EventBase().

640  {
641  // Infinite size queue
642  queue_ = std::make_unique<NotificationQueue<Func>>();
643 
644  // We allocate fnRunner_ separately, rather than declaring it directly
645  // as a member of EventBase solely so that we don't need to include
646  // NotificationQueue.h from EventBase.h
647  fnRunner_ = std::make_unique<FunctionRunner>();
648 
649  // Mark this as an internal event, so event_base_loop() will return if
650  // there are no other events besides this one installed.
651  //
652  // Most callers don't care about the internal notification queue used by
653  // EventBase. The queue is always installed, so if we did count the queue as
654  // an active event, loop() would never exit with no more events to process.
655  // Users can use loopForever() if they do care about the notification queue.
656  // (This is useful for EventBase threads that do nothing but process
657  // runInEventBaseThread() notifications.)
658  fnRunner_->startConsumingInternal(this, queue_.get());
659 }
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735
bool folly::EventBase::inRunningEventBaseThread ( ) const
inline

Definition at line 509 of file EventBase.h.

Referenced by runInEventBaseThread(), and runInEventBaseThreadAndWait().

509  {
510  return loopThread_.load(std::memory_order_relaxed) ==
511  std::this_thread::get_id();
512  }
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
bool folly::EventBase::isInEventBaseThread ( ) const
inline

Verify that current thread is the EventBase thread, if the EventBase is running.

Definition at line 504 of file EventBase.h.

Referenced by folly::AsyncUDPSocket::attachEventBase(), folly::AsyncUDPSocket::detachEventBase(), wangle::Acceptor::dropAllConnections(), folly::AttachDetachClient::readDataAvailable(), runImmediatelyOrRunInEventBaseThreadAndWait(), UDPServer::shutdown(), UDPClient::shutdown(), UDPServer::start(), and UDPClient::start().

504  {
505  auto tid = loopThread_.load(std::memory_order_relaxed);
506  return tid == std::thread::id() || tid == std::this_thread::get_id();
507  }
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
bool folly::EventBase::isInTimeoutManagerThread ( )
inlinefinalvirtual

Helper method to know whether we are running in the timeout manager thread

Implements folly::TimeoutManager.

Definition at line 654 of file EventBase.h.

References folly::getEventBase().

654  {
655  return isInEventBaseThread();
656  }
bool isInEventBaseThread() const
Definition: EventBase.h:504
bool folly::EventBase::isRunning ( ) const
inline

check if the event base loop is running.

Definition at line 487 of file EventBase.h.

References uint32_t.

Referenced by setName(), and waitUntilRunning().

487  {
488  return loopThread_.load(std::memory_order_relaxed) != std::thread::id();
489  }
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
bool folly::EventBase::keepAliveAcquire ( )
inlineoverrideprotectedvirtual

Reimplemented from folly::Executor.

Definition at line 671 of file EventBase.h.

671  {
672  if (inRunningEventBaseThread()) {
674  } else {
675  loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
676  }
677  return true;
678  }
bool inRunningEventBaseThread() const
Definition: EventBase.h:509
ssize_t loopKeepAliveCount_
Definition: EventBase.h:736
std::atomic< ssize_t > loopKeepAliveCountAtomic_
Definition: EventBase.h:737
void folly::EventBase::keepAliveRelease ( )
inlineoverrideprotectedvirtual

Reimplemented from folly::Executor.

Definition at line 680 of file EventBase.h.

References add, and folly::pushmi::__adl::noexcept().

680  {
681  if (!inRunningEventBaseThread()) {
682  return add([this] { loopKeepAliveCount_--; });
683  }
685  }
void add(Cob fn) override
Implements the Executor interface.
Definition: EventBase.h:624
bool inRunningEventBaseThread() const
Definition: EventBase.h:509
ssize_t loopKeepAliveCount_
Definition: EventBase.h:736
bool folly::EventBase::loop ( )

Runs the event loop.

loop() will loop waiting for I/O or timeouts and invoking EventHandler and AsyncTimeout callbacks as their events become ready. loop() will only return when there are no more events remaining to process, or after terminateLoopSoon() has been called.

loop() may be called again to restart event processing after a previous call to loop() or loopForever() has returned.

Returns true if the loop completed normally (if it processed all outstanding requests, or if terminateLoopSoon() was called). If an error occurs waiting for events, false will be returned.

Definition at line 256 of file EventBase.cpp.

References loopBody().

Referenced by BENCHMARK(), BENCHMARK_RELATIVE(), QueueTest::destroyCallback(), fizz::test::HandshakeTest::doClientHandshake(), fizz::test::HandshakeTest::doHandshake(), fizz::test::HandshakeTest::doServerHandshake(), fizz::tool::fizzClientCommand(), fizz::tool::fizzServerCommand(), folly::TestSSLServer::init(), loopForever(), main(), QueueTest::maxReadAtOnce(), QueueTest::multiConsumer(), BlockingSocket::open(), QueueTest::putMessages(), ClientRunner::run(), proxygen::WorkerThread::runLoop(), QueueTest::sendOne(), serverSocketSanityTest(), serverTest(), wangle::TEST(), fizz::server::test::TEST(), folly::TEST(), TEST(), TEST_F(), fizz::client::test::TEST_F(), TEST_P(), testConnectOptWrite(), and BlockingSocket::write().

256  {
257  return loopBody();
258 }
bool loopBody(int flags=0, bool ignoreKeepAlive=false)
Definition: EventBase.cpp:275
bool folly::EventBase::loopBody ( int  flags = 0,
bool  ignoreKeepAlive = false 
)
private

Definition at line 275 of file EventBase.cpp.

References folly::EventBase::SmoothLoopTime::addSample(), applyLoopKeepAlive(), avgLoopTime_, folly::EventBase::SmoothLoopTime::dampen(), enableTimeMeasurement_, evb_, fnRunner_, folly::EventBase::SmoothLoopTime::get(), getNotificationQueueSize(), folly::getTimeDelta(), invokingLoop_, loopCallbacks_, loopThread_, maxLatency_, maxLatencyCob_, maxLatencyLoopTime_, name_, nextLoopCnt_, nothingHandledYet(), now(), folly::ScheduledExecutor::now(), observer_, observerSampleCount_, runBeforeLoopCallbacks_, runLoopCallbacks(), SCOPE_EXIT, folly::setThreadName(), startWork_, and stop_.

Referenced by loop(), loopIgnoreKeepAlive(), and loopOnce().

275  {
276  VLOG(5) << "EventBase(): Starting loop.";
277 
278  DCHECK(!invokingLoop_)
279  << "Your code just tried to loop over an event base from inside another "
280  << "event base loop. Since libevent is not reentrant, this leads to "
281  << "undefined behavior in opt builds. Please fix immediately. For the "
282  << "common case of an inner function that needs to do some synchronous "
283  << "computation on an event-base, replace getEventBase() by a new, "
284  << "stack-allocated EvenBase.";
285  invokingLoop_ = true;
286  SCOPE_EXIT {
287  invokingLoop_ = false;
288  };
289 
290  int res = 0;
291  bool ranLoopCallbacks;
292  bool blocking = !(flags & EVLOOP_NONBLOCK);
293  bool once = (flags & EVLOOP_ONCE);
294 
295  // time-measurement variables.
296  std::chrono::steady_clock::time_point prev;
297  std::chrono::steady_clock::time_point idleStart = {};
298  std::chrono::microseconds busy;
299  std::chrono::microseconds idle;
300 
301  loopThread_.store(std::this_thread::get_id(), std::memory_order_release);
302 
303  if (!name_.empty()) {
305  }
306 
309  idleStart = prev;
310  }
311 
312  while (!stop_.load(std::memory_order_relaxed)) {
313  if (!ignoreKeepAlive) {
315  }
316  ++nextLoopCnt_;
317 
318  // Run the before loop callbacks
319  LoopCallbackList callbacks;
320  callbacks.swap(runBeforeLoopCallbacks_);
321 
322  while (!callbacks.empty()) {
323  auto* item = &callbacks.front();
324  callbacks.pop_front();
325  item->runLoopCallback();
326  }
327 
328  // nobody can add loop callbacks from within this thread if
329  // we don't have to handle anything to start with...
330  if (blocking && loopCallbacks_.empty()) {
331  res = event_base_loop(evb_, EVLOOP_ONCE);
332  } else {
333  res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
334  }
335 
336  ranLoopCallbacks = runLoopCallbacks();
337 
340  busy = std::chrono::duration_cast<std::chrono::microseconds>(
341  now - startWork_);
342  idle = std::chrono::duration_cast<std::chrono::microseconds>(
343  startWork_ - idleStart);
344  auto loop_time = busy + idle;
345 
346  avgLoopTime_.addSample(loop_time, busy);
347  maxLatencyLoopTime_.addSample(loop_time, busy);
348 
349  if (observer_) {
350  if (observerSampleCount_++ == observer_->getSampleRate()) {
352  observer_->loopSample(busy.count(), idle.count());
353  }
354  }
355 
356  VLOG(11) << "EventBase " << this << " did not timeout "
357  << " loop time guess: " << loop_time.count()
358  << " idle time: " << idle.count()
359  << " busy time: " << busy.count()
360  << " avgLoopTime: " << avgLoopTime_.get()
361  << " maxLatencyLoopTime: " << maxLatencyLoopTime_.get()
362  << " maxLatency_: " << maxLatency_.count() << "us"
363  << " notificationQueueSize: " << getNotificationQueueSize()
364  << " nothingHandledYet(): " << nothingHandledYet();
365 
366  // see if our average loop time has exceeded our limit
367  if ((maxLatency_ > std::chrono::microseconds::zero()) &&
368  (maxLatencyLoopTime_.get() > double(maxLatency_.count()))) {
369  maxLatencyCob_();
370  // back off temporarily -- don't keep spamming maxLatencyCob_
371  // if we're only a bit over the limit
373  }
374 
375  // Our loop run did real work; reset the idle timer
376  idleStart = now;
377  } else {
378  VLOG(11) << "EventBase " << this << " did not timeout";
379  }
380 
381  // If the event loop indicate that there were no more events, and
382  // we also didn't have any loop callbacks to run, there is nothing left to
383  // do.
384  if (res != 0 && !ranLoopCallbacks) {
385  // Since Notification Queue is marked 'internal' some events may not have
386  // run. Run them manually if so, and continue looping.
387  //
388  if (getNotificationQueueSize() > 0) {
389  fnRunner_->handlerReady(0);
390  } else {
391  break;
392  }
393  }
394 
396  VLOG(11) << "EventBase " << this
397  << " loop time: " << getTimeDelta(&prev).count();
398  }
399 
400  if (once) {
401  break;
402  }
403  }
404  // Reset stop_ so loop() can be called again
405  stop_.store(false, std::memory_order_relaxed);
406 
407  if (res < 0) {
408  LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
409  return false;
410  } else if (res == 1) {
411  VLOG(5) << "EventBase: ran out of events (exiting loop)!";
412  } else if (res > 1) {
413  LOG(ERROR) << "EventBase: unknown event loop result = " << res;
414  return false;
415  }
416 
417  loopThread_.store({}, std::memory_order_release);
418 
419  VLOG(5) << "EventBase(): Done with loop.";
420  return true;
421 }
std::chrono::microseconds maxLatency_
Definition: EventBase.h:741
flags
Definition: http_parser.h:127
LoopCallbackList runBeforeLoopCallbacks_
Definition: EventBase.h:712
size_t getNotificationQueueSize() const
Definition: EventBase.cpp:197
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
std::chrono::steady_clock::time_point now()
bool runLoopCallbacks()
Definition: EventBase.cpp:612
void applyLoopKeepAlive()
Definition: EventBase.cpp:433
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
std::string name_
Definition: EventBase.h:777
virtual TimePoint now()
Get this executor&#39;s notion of time. Must be threadsafe.
void addSample(std::chrono::microseconds total, std::chrono::microseconds busy)
Definition: EventBase.cpp:671
std::shared_ptr< EventBaseObserver > observer_
Definition: EventBase.h:770
LoopCallback::List LoopCallbackList
Definition: EventBase.h:698
event_base * evb_
Definition: EventBase.h:730
std::chrono::steady_clock::time_point startWork_
Definition: EventBase.h:762
SmoothLoopTime maxLatencyLoopTime_
Definition: EventBase.h:749
std::atomic< bool > stop_
Definition: EventBase.h:723
bool setThreadName(std::thread::id tid, StringPiece name)
Definition: ThreadName.cpp:109
const bool enableTimeMeasurement_
Definition: EventBase.h:757
std::size_t nextLoopCnt_
Definition: EventBase.h:760
void dampen(double factor)
Definition: EventBase.h:574
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735
LoopCallbackList loopCallbacks_
Definition: EventBase.h:711
static std::chrono::milliseconds getTimeDelta(std::chrono::steady_clock::time_point *prev)
Definition: EventBase.cpp:241
SmoothLoopTime avgLoopTime_
Definition: EventBase.h:744
bool nothingHandledYet() const noexcept
Definition: EventBase.cpp:689
uint32_t observerSampleCount_
Definition: EventBase.h:771
void folly::EventBase::loopForever ( )

Runs the event loop.

loopForever() behaves like loop(), except that it keeps running even if when there are no more user-supplied EventHandlers or AsyncTimeouts registered. It will only return after terminateLoopSoon() has been called.

This is useful for callers that want to wait for other threads to call runInEventBaseThread(), even when there are no other scheduled events.

loopForever() may be called again to restart event processing after a previous call to loop() or loopForever() has returned.

Throws a std::system_error if an error occurs.

Definition at line 455 of file EventBase.cpp.

References applyLoopKeepAlive(), loop(), loopKeepAliveCount_, SCOPE_EXIT, and folly::throwSystemError().

Referenced by folly::run(), folly::ZeroCopyTest::run(), proxygen::WorkerThread::runLoop(), runTest(), proxygen::HTTPServer::start(), wangle::TEST(), TEST(), folly::TEST(), TEST_F(), and folly::ThreadWheelTimekeeper::ThreadWheelTimekeeper().

455  {
456  bool ret;
457  {
458  SCOPE_EXIT {
460  };
461  // Make sure notification queue events are treated as normal events.
462  // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
463  // released inside a loop.
465  SCOPE_EXIT {
467  };
468  ret = loop();
469  }
470 
471  if (!ret) {
472  folly::throwSystemError("error in EventBase::loopForever()");
473  }
474 }
void applyLoopKeepAlive()
Definition: EventBase.cpp:433
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
ssize_t loopKeepAliveCount_
Definition: EventBase.h:736
void throwSystemError(Args &&...args)
Definition: Exception.h:76
bool folly::EventBase::loopIgnoreKeepAlive ( )

Same as loop(), but doesn't wait for all keep-alive tokens to be released.

Definition at line 260 of file EventBase.cpp.

References fnRunner_, loopBody(), loopKeepAliveActive_, and queue_.

260  {
261  if (loopKeepAliveActive_) {
262  // Make sure NotificationQueue is not counted as one of the readers
263  // (otherwise loopBody won't return until terminateLoopSoon is called).
264  fnRunner_->stopConsuming();
265  fnRunner_->startConsumingInternal(this, queue_.get());
266  loopKeepAliveActive_ = false;
267  }
268  return loopBody(0, true);
269 }
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
bool loopBody(int flags=0, bool ignoreKeepAlive=false)
Definition: EventBase.cpp:275
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735
bool loopKeepAliveActive_
Definition: EventBase.h:738
ssize_t folly::EventBase::loopKeepAliveCount ( )
private

Definition at line 423 of file EventBase.cpp.

References loopKeepAliveCount_, and loopKeepAliveCountAtomic_.

Referenced by applyLoopKeepAlive(), and ~EventBase().

423  {
424  if (loopKeepAliveCountAtomic_.load(std::memory_order_relaxed)) {
426  loopKeepAliveCountAtomic_.exchange(0, std::memory_order_relaxed);
427  }
428  DCHECK_GE(loopKeepAliveCount_, 0);
429 
430  return loopKeepAliveCount_;
431 }
ssize_t loopKeepAliveCount_
Definition: EventBase.h:736
std::atomic< ssize_t > loopKeepAliveCountAtomic_
Definition: EventBase.h:737
bool folly::EventBase::loopOnce ( int  flags = 0)

Wait for some events to become active, run them, then return.

When EVLOOP_NONBLOCK is set in flags, the loop won't block if there are not any events to process.

This is useful for callers that want to run the loop manually.

Returns the same result as loop().

Definition at line 271 of file EventBase.cpp.

References loopBody().

Referenced by BlockingSocket::readHelper(), folly::TEST(), TEST(), TEST_F(), and ~EventBase().

271  {
272  return loopBody(flags | EVLOOP_ONCE);
273 }
flags
Definition: http_parser.h:127
bool loopBody(int flags=0, bool ignoreKeepAlive=false)
Definition: EventBase.cpp:275
bool folly::EventBase::nothingHandledYet ( ) const
privatenoexcept

Definition at line 689 of file EventBase.cpp.

References latestLoopCnt_, and nextLoopCnt_.

Referenced by bumpHandlingTime(), and loopBody().

689  {
690  VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
691  return (nextLoopCnt_ != latestLoopCnt_);
692 }
std::size_t nextLoopCnt_
Definition: EventBase.h:760
std::size_t latestLoopCnt_
Definition: EventBase.h:761
void folly::EventBase::resetLoadAvg ( double  value = 0.0)

reset the load average to a desired value

Definition at line 235 of file EventBase.cpp.

References avgLoopTime_, enableTimeMeasurement_, maxLatencyLoopTime_, and folly::EventBase::SmoothLoopTime::reset().

Referenced by TEST().

235  {
236  assert(enableTimeMeasurement_);
239 }
void reset(double value=0.0)
Definition: EventBase.cpp:667
SmoothLoopTime maxLatencyLoopTime_
Definition: EventBase.h:749
const bool enableTimeMeasurement_
Definition: EventBase.h:757
uint64_t value(const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
SmoothLoopTime avgLoopTime_
Definition: EventBase.h:744
void folly::EventBase::runBeforeLoop ( LoopCallback callback)

Adds a callback that will run immediately before the event loop. This is very similar to runInLoop(), but will not cause the loop to break: For example, this callback could be used to get loop times.

Definition at line 548 of file EventBase.cpp.

References folly::EventBase::LoopCallback::cancelLoopCallback(), dcheckIsInEventBaseThread(), and runBeforeLoopCallbacks_.

Referenced by folly::MemoryIdlerTimeout::runLoopCallback(), and TEST().

548  {
550  callback->cancelLoopCallback();
551  runBeforeLoopCallbacks_.push_back(*callback);
552 }
LoopCallbackList runBeforeLoopCallbacks_
Definition: EventBase.h:712
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
template<typename T >
bool folly::EventBase::runImmediatelyOrRunInEventBaseThreadAndWait ( void(*)(T *)  fn,
T arg 
)

Definition at line 804 of file EventBase.h.

Referenced by wangle::AsyncServerSocketFactory::ThreadSafeDestructor::operator()(), wangle::AsyncUDPServerSocketFactory::ThreadSafeDestructor::operator()(), and TEST().

806  {
807  return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });
808 }
bool runImmediatelyOrRunInEventBaseThreadAndWait(void(*fn)(T *), T *arg)
Definition: EventBase.h:804
bool folly::EventBase::runImmediatelyOrRunInEventBaseThreadAndWait ( Func  fn)

Definition at line 603 of file EventBase.cpp.

References isInEventBaseThread(), folly::gen::move, and runInEventBaseThreadAndWait().

603  {
604  if (isInEventBaseThread()) {
605  fn();
606  return true;
607  } else {
609  }
610 }
bool runInEventBaseThreadAndWait(void(*fn)(T *), T *arg)
Definition: EventBase.h:799
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool isInEventBaseThread() const
Definition: EventBase.h:504
template<typename T >
bool folly::EventBase::runInEventBaseThread ( void(*)(T *)  fn,
T arg 
)

Run the specified function in the EventBase's thread.

This method is thread-safe, and may be called from another thread.

If runInEventBaseThread() is called when the EventBase loop is not running, the function call will be delayed until the next time the loop is started.

If runInEventBaseThread() returns true the function has successfully been scheduled to run in the loop thread. However, if the loop is terminated (and never later restarted) before it has a chance to run the requested function, the function will be run upon the EventBase's destruction.

If two calls to runInEventBaseThread() are made from the same thread, the functions will always be run in the order that they were scheduled. Ordering between functions scheduled from separate threads is not guaranteed.

Parameters
fnThe function to run. The function must not throw any exceptions.
argAn argument to pass to the function.
Returns
Returns true if the function was successfully scheduled, or false if there was an error scheduling the function.

Definition at line 794 of file EventBase.h.

Referenced by folly::ThreadWheelTimekeeper::after(), AcceptRoutingHandlerTest::clientConnectAndCleanClose(), AcceptRoutingHandlerTest::clientConnectAndWrite(), folly::AttachDetachClient::connect(), wangle::EvbHandshakeHelper::connectionError(), wangle::EvbHandshakeHelper::connectionReady(), folly::AttachDetachClient::connectSuccess(), wangle::EvbHandshakeHelper::dropConnection(), wangle::Acceptor::dropConnections(), proxygen::WorkerThread::forceStop(), wangle::Acceptor::forceStop(), AcceptRoutingHandlerTest::justClientConnect(), QueueTest::multiConsumer(), StaticService::StaticHandler::readFile(), folly::ZeroCopyTest::run(), runInEventBaseThreadAndWait(), runTest(), AcceptRoutingHandlerTest::sendClientException(), QueueTest::sendOne(), folly::AsyncServerSocket::RemoteAcceptor::start(), folly::AsyncServerSocket::RemoteAcceptor::stop(), proxygen::WorkerThread::stopWhenIdle(), TEST(), folly::TEST(), TEST_F(), proxygen::HandlerCallbacks::threadStopped(), folly::ThreadWheelTimekeeper::ThreadWheelTimekeeper(), proxygen::HTTPServer::updateTicketSeeds(), proxygen::HTTPServer::updateTLSCredentials(), and folly::TestSSLServer::~TestSSLServer().

794  {
795  return runInEventBaseThread([=] { fn(arg); });
796 }
bool runInEventBaseThread(void(*fn)(T *), T *arg)
Definition: EventBase.h:794
bool folly::EventBase::runInEventBaseThread ( Func  fn)

Run the specified function in the EventBase's thread

This version of runInEventBaseThread() takes a folly::Function object. Note that this may be less efficient than the version that takes a plain function pointer and void* argument, if moving the function is expensive (e.g., if it wraps a lambda which captures some values with expensive move constructors).

If the loop is terminated (and never later restarted) before it has a chance to run the requested function, the function will be run upon the EventBase's destruction.

The function must not throw any exceptions.

Definition at line 554 of file EventBase.cpp.

References inRunningEventBaseThread(), folly::gen::move, queue_, and runInLoop().

554  {
555  // Send the message.
556  // It will be received by the FunctionRunner in the EventBase's thread.
557 
558  // We try not to schedule nullptr callbacks
559  if (!fn) {
560  LOG(ERROR) << "EventBase " << this
561  << ": Scheduling nullptr callbacks is not allowed";
562  return false;
563  }
564 
565  // Short-circuit if we are already in our event base
566  if (inRunningEventBaseThread()) {
567  runInLoop(std::move(fn));
568  return true;
569  }
570 
571  try {
572  queue_->putMessage(std::move(fn));
573  } catch (const std::exception& ex) {
574  LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
575  << "for EventBase thread: " << ex.what();
576  return false;
577  }
578 
579  return true;
580 }
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool inRunningEventBaseThread() const
Definition: EventBase.h:509
void runInLoop(LoopCallback *callback, bool thisIteration=false)
Definition: EventBase.cpp:520
template<typename T >
bool folly::EventBase::runInEventBaseThreadAndWait ( void(*)(T *)  fn,
T arg 
)

Definition at line 799 of file EventBase.h.

Referenced by runImmediatelyOrRunInEventBaseThreadAndWait(), TEST(), TEST_F(), and folly::ThreadWheelTimekeeper::~ThreadWheelTimekeeper().

799  {
800  return runInEventBaseThreadAndWait([=] { fn(arg); });
801 }
bool runInEventBaseThreadAndWait(void(*fn)(T *), T *arg)
Definition: EventBase.h:799
bool folly::EventBase::runInEventBaseThreadAndWait ( Func  fn)

Definition at line 582 of file EventBase.cpp.

References folly::copy(), inRunningEventBaseThread(), folly::gen::move, folly::Baton< MayBlock, Atom >::post(), runInEventBaseThread(), SCOPE_EXIT, and folly::Baton< MayBlock, Atom >::wait().

582  {
583  if (inRunningEventBaseThread()) {
584  LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
585  << "allowed";
586  return false;
587  }
588 
589  Baton<> ready;
590  runInEventBaseThread([&ready, fn = std::move(fn)]() mutable {
591  SCOPE_EXIT {
592  ready.post();
593  };
594  // A trick to force the stored functor to be executed and then destructed
595  // before posting the baton and waking the waiting thread.
596  copy(std::move(fn))();
597  });
598  ready.wait();
599 
600  return true;
601 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
bool inRunningEventBaseThread() const
Definition: EventBase.h:509
constexpr std::decay< T >::type copy(T &&value) noexcept(noexcept(typename std::decay< T >::type(std::forward< T >(value))))
Definition: Utility.h:72
bool runInEventBaseThread(void(*fn)(T *), T *arg)
Definition: EventBase.h:794
void folly::EventBase::runInLoop ( LoopCallback callback,
bool  thisIteration = false 
)

Adds the given callback to a queue of things run after the current pass through the event loop completes. Note that if this callback calls runInLoop() the new callback won't be called until the main event loop has gone through a cycle.

This method may only be called from the EventBase's thread. This essentially allows an event handler to schedule an additional callback to be invoked after it returns.

Use runInEventBaseThread() to schedule functions from another thread.

The thisIteration parameter makes this callback run in this loop iteration, instead of the next one, even if called from a runInLoop callback (normal io callbacks that call runInLoop will always run in this iteration). This was originally added to support detachEventBase, as a user callback may have called terminateLoopSoon(), but we want to make sure we detach. Also, detachEventBase almost always must be called from the base event loop to ensure the stack is unwound, since most users of EventBase are not thread safe.

Ideally we would not need thisIteration, and instead just use runInLoop with loop() (instead of terminateLoopSoon).

Definition at line 520 of file EventBase.cpp.

References folly::EventBase::LoopCallback::cancelLoopCallback(), folly::EventBase::LoopCallback::context_, dcheckIsInEventBaseThread(), loopCallbacks_, runOnceCallbacks_, and folly::RequestContext::saveContext().

Referenced by BENCHMARK(), BENCHMARK_RELATIVE(), TestAsyncTransport::fireNextReadEvent(), fizz::tool::TerminalInputHandler::hitEOF(), QueueTest::maxReadAtOnce(), folly::ZeroCopyTestAsyncSocket::onDataReady(), runInEventBaseThread(), folly::fibers::EventBaseLoopController::schedule(), folly::AsyncSocket::scheduleImmediateRead(), folly::AsyncSocket::scheduleInitialReadWrite(), proxygen::HTTPServer::start(), TEST(), and tmpDisableReads().

520  {
522  callback->cancelLoopCallback();
523  callback->context_ = RequestContext::saveContext();
524  if (runOnceCallbacks_ != nullptr && thisIteration) {
525  runOnceCallbacks_->push_back(*callback);
526  } else {
527  loopCallbacks_.push_back(*callback);
528  }
529 }
LoopCallbackList * runOnceCallbacks_
Definition: EventBase.h:719
static std::shared_ptr< RequestContext > saveContext()
Definition: Request.h:196
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
LoopCallbackList loopCallbacks_
Definition: EventBase.h:711
void folly::EventBase::runInLoop ( Func  c,
bool  thisIteration = false 
)

Convenience function to call runInLoop() with a folly::Function.

This creates a LoopCallback object to wrap the folly::Function, and invoke the folly::Function when the loop callback fires. This is slightly more expensive than defining your own LoopCallback, but more convenient in areas that aren't too performance sensitive.

This method may only be called from the EventBase's thread. This essentially allows an event handler to schedule an additional callback to be invoked after it returns.

Use runInEventBaseThread() to schedule functions from another thread.

Definition at line 531 of file EventBase.cpp.

References dcheckIsInEventBaseThread(), loopCallbacks_, folly::gen::move, runOnceCallbacks_, and folly::RequestContext::saveContext().

531  {
533  auto wrapper = new FunctionLoopCallback(std::move(cob));
534  wrapper->context_ = RequestContext::saveContext();
535  if (runOnceCallbacks_ != nullptr && thisIteration) {
536  runOnceCallbacks_->push_back(*wrapper);
537  } else {
538  loopCallbacks_.push_back(*wrapper);
539  }
540 }
LoopCallbackList * runOnceCallbacks_
Definition: EventBase.h:719
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
static std::shared_ptr< RequestContext > saveContext()
Definition: Request.h:196
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
LoopCallbackList loopCallbacks_
Definition: EventBase.h:711
bool folly::EventBase::runLoopCallbacks ( )
private

Definition at line 612 of file EventBase.cpp.

References bumpHandlingTime(), folly::EventBase::LoopCallback::context_, loopCallbacks_, folly::gen::move, folly::EventBase::LoopCallback::runLoopCallback(), and runOnceCallbacks_.

Referenced by loopBody(), and ~EventBase().

612  {
614  if (!loopCallbacks_.empty()) {
615  // Swap the loopCallbacks_ list with a temporary list on our stack.
616  // This way we will only run callbacks scheduled at the time
617  // runLoopCallbacks() was invoked.
618  //
619  // If any of these callbacks in turn call runInLoop() to schedule more
620  // callbacks, those new callbacks won't be run until the next iteration
621  // around the event loop. This prevents runInLoop() callbacks from being
622  // able to start file descriptor and timeout based events.
623  LoopCallbackList currentCallbacks;
624  currentCallbacks.swap(loopCallbacks_);
625  runOnceCallbacks_ = &currentCallbacks;
626 
627  while (!currentCallbacks.empty()) {
628  LoopCallback* callback = &currentCallbacks.front();
629  currentCallbacks.pop_front();
630  folly::RequestContextScopeGuard rctx(std::move(callback->context_));
631  callback->runLoopCallback();
632  }
633 
634  runOnceCallbacks_ = nullptr;
635  return true;
636  }
637  return false;
638 }
LoopCallbackList * runOnceCallbacks_
Definition: EventBase.h:719
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void bumpHandlingTime() final
Definition: EventBase.cpp:476
LoopCallback::List LoopCallbackList
Definition: EventBase.h:698
LoopCallbackList loopCallbacks_
Definition: EventBase.h:711
void folly::EventBase::runOnDestruction ( LoopCallback callback)

Adds the given callback to a queue of things run before destruction of current EventBase.

This allows users of EventBase that run in it, but don't control it, to be notified before EventBase gets destructed.

Note: will be called from the thread that invoked EventBase destructor, before the final run of loop callbacks.

Definition at line 542 of file EventBase.cpp.

References folly::EventBase::LoopCallback::cancelLoopCallback(), onDestructionCallbacks_, and onDestructionCallbacksMutex_.

Referenced by folly::run(), and TEST_F().

542  {
543  std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
544  callback->cancelLoopCallback();
545  onDestructionCallbacks_.push_back(*callback);
546 }
LoopCallbackList onDestructionCallbacks_
Definition: EventBase.h:713
std::mutex onDestructionCallbacksMutex_
Definition: EventBase.h:780
void folly::EventBase::scheduleAt ( Func &&  ,
TimePoint const &   
)
overridevirtual

Schedule a Func to be executed at time t, or as soon afterward as possible. Expect millisecond resolution at best. Must be threadsafe.

Reimplemented from folly::ScheduledExecutor.

Definition at line 754 of file EventBase.cpp.

References folly::gen::move, folly::ScheduledExecutor::now(), folly::HHWheelTimer::scheduleTimeoutFn(), and timer().

Referenced by fizz::server::test::TEST(), and TEST().

754  {
755  auto duration = timeout - now();
757  std::move(fn),
758  std::chrono::duration_cast<std::chrono::milliseconds>(duration));
759 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
virtual TimePoint now()
Get this executor&#39;s notion of time. Must be threadsafe.
void scheduleTimeoutFn(F fn, std::chrono::milliseconds timeout)
Definition: HHWheelTimer.h:229
HHWheelTimer & timer()
Definition: EventBase.h:526
bool folly::EventBase::scheduleTimeout ( AsyncTimeout obj,
TimeoutManager::timeout_type  timeout 
)
finalvirtual

Schedules AsyncTimeout to fire after timeout milliseconds

Implements folly::TimeoutManager.

Definition at line 711 of file EventBase.cpp.

References dcheckIsInEventBaseThread(), folly::errnoStr(), and folly::AsyncTimeout::getEvent().

713  {
715  // Set up the timeval and add the event
716  struct timeval tv;
717  tv.tv_sec = long(timeout.count() / 1000LL);
718  tv.tv_usec = long((timeout.count() % 1000LL) * 1000LL);
719 
720  struct event* ev = obj->getEvent();
721 
722  DCHECK(ev->ev_base);
723 
724  if (event_add(ev, &tv) < 0) {
725  LOG(ERROR) << "EventBase: failed to schedule timeout: " << errnoStr(errno);
726  return false;
727  }
728 
729  return true;
730 }
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
fbstring errnoStr(int err)
Definition: String.cpp:463
void folly::EventBase::setExecutionObserver ( ExecutionObserver observer)
inline

Setup execution observation/instrumentation for every EventHandler executed in this EventBase.

Parameters
executionObserverEventHandle's execution observer.

Definition at line 602 of file EventBase.h.

602  {
603  executionObserver_ = observer;
604  }
ExecutionObserver * executionObserver_
Definition: EventBase.h:774
void folly::EventBase::setLoadAvgMsec ( std::chrono::milliseconds  ms)

Set smoothing coefficient for loop load average; # of milliseconds for exp(-1) (1/2.71828...) decay.

Definition at line 224 of file EventBase.cpp.

References avgLoopTime_, enableTimeMeasurement_, maxLatencyLoopTime_, folly::EventBase::SmoothLoopTime::setTimeInterval(), and us.

Referenced by TEST().

224  {
225  assert(enableTimeMeasurement_);
226  std::chrono::microseconds us = std::chrono::milliseconds(ms);
227  if (ms > std::chrono::milliseconds::zero()) {
230  } else {
231  LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
232  }
233 }
void setTimeInterval(std::chrono::microseconds timeInterval)
Definition: EventBase.cpp:661
SmoothLoopTime maxLatencyLoopTime_
Definition: EventBase.h:749
const bool enableTimeMeasurement_
Definition: EventBase.h:757
SmoothLoopTime avgLoopTime_
Definition: EventBase.h:744
static unordered_set< string > us
void folly::EventBase::setMaxLatency ( std::chrono::microseconds  maxLatency,
Func  maxLatencyCob 
)
inline

Set the maximum desired latency in us and provide a callback which will be called when that latency is exceeded. OBS: This functionality depends on time-measurement.

Definition at line 459 of file EventBase.h.

References folly::gen::move, and folly::value().

Referenced by TEST().

459  {
460  assert(enableTimeMeasurement_);
461  maxLatency_ = maxLatency;
462  maxLatencyCob_ = std::move(maxLatencyCob);
463  }
std::chrono::microseconds maxLatency_
Definition: EventBase.h:741
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const bool enableTimeMeasurement_
Definition: EventBase.h:757
void folly::EventBase::setMaxReadAtOnce ( uint32_t  maxAtOnce)

Definition at line 201 of file EventBase.cpp.

References fnRunner_.

Referenced by runTest().

201  {
202  fnRunner_->setMaxReadAtOnce(maxAtOnce);
203 }
std::unique_ptr< FunctionRunner > fnRunner_
Definition: EventBase.h:735
void folly::EventBase::setName ( const std::string name)

Set the name of the thread that runs this event base.

Definition at line 740 of file EventBase.cpp.

References dcheckIsInEventBaseThread(), isRunning(), loopThread_, name, name_, and folly::setThreadName().

Referenced by TEST(), folly::ThreadWheelTimekeeper::ThreadWheelTimekeeper(), and proxygen::WorkerThread::WorkerThread().

740  {
742  name_ = name;
743 
744  if (isRunning()) {
745  setThreadName(loopThread_.load(std::memory_order_relaxed), name_);
746  }
747 }
std::atomic< std::thread::id > loopThread_
Definition: EventBase.h:727
std::string name_
Definition: EventBase.h:777
const char * name
Definition: http_parser.c:437
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
bool setThreadName(std::thread::id tid, StringPiece name)
Definition: ThreadName.cpp:109
bool isRunning() const
Definition: EventBase.h:487
void folly::EventBase::setObserver ( const std::shared_ptr< EventBaseObserver > &  observer)
inline

Definition at line 587 of file EventBase.h.

587  {
588  assert(enableTimeMeasurement_);
589  observer_ = observer;
590  }
std::shared_ptr< EventBaseObserver > observer_
Definition: EventBase.h:770
const bool enableTimeMeasurement_
Definition: EventBase.h:757
void folly::EventBase::terminateLoopSoon ( )

Causes the event loop to exit soon.

This will cause an existing call to loop() or loopForever() to stop event processing and return, even if there are still events remaining to be processed.

It is safe to call terminateLoopSoon() from another thread to cause loop() to wake up and return in the EventBase loop thread. terminateLoopSoon() may also be called from the loop thread itself (for example, a EventHandler or AsyncTimeout callback may call terminateLoopSoon() to cause the loop to exit after the callback returns.) If the loop is not running, this will cause the next call to loop to terminate soon after starting. If a loop runs out of work (and so terminates on its own) concurrently with a call to terminateLoopSoon(), this may cause a race condition.

Note that the caller is responsible for ensuring that cleanup of all event callbacks occurs properly. Since terminateLoopSoon() causes the loop to exit even when there are pending events present, there may be remaining callbacks present waiting to be invoked. If the loop is later restarted pending events will continue to be processed normally, however if the EventBase is destroyed after calling terminateLoopSoon() it is the caller's responsibility to ensure that cleanup happens properly even if some outstanding events are never processed.

Definition at line 493 of file EventBase.cpp.

References evb_, queue_, and stop_.

Referenced by proxygen::WorkerThread::forceStop(), QueueTest::maxReadAtOnce(), folly::ZeroCopyTestAsyncSocket::onDataFinish(), folly::ZeroCopyTestAsyncSocket::onDataReady(), TestAcceptor::onNewConnection(), runInThreadTestFunc(), runTest(), UDPClient::shutdown(), proxygen::HTTPServer::stop(), proxygen::WorkerThread::stopWhenIdle(), fizz::server::test::TEST(), wangle::TEST(), TEST(), folly::TEST(), TEST_F(), folly::ScopedEventBaseThread::~ScopedEventBaseThread(), and folly::ThreadWheelTimekeeper::~ThreadWheelTimekeeper().

493  {
494  VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
495 
496  // Set stop to true, so the event loop will know to exit.
497  stop_.store(true, std::memory_order_relaxed);
498 
499  // Call event_base_loopbreak() so that libevent will exit the next time
500  // around the loop.
501  event_base_loopbreak(evb_);
502 
503  // If terminateLoopSoon() is called from another thread,
504  // the EventBase thread might be stuck waiting for events.
505  // In this case, it won't wake up and notice that stop_ is set until it
506  // receives another event. Send an empty frame to the notification queue
507  // so that the event loop will wake up even if there are no other events.
508  //
509  // We don't care about the return value of trySendFrame(). If it fails
510  // this likely means the EventBase already has lots of events waiting
511  // anyway.
512  try {
513  queue_->putMessage(nullptr);
514  } catch (...) {
515  // We don't care if putMessage() fails. This likely means
516  // the EventBase already has lots of events waiting anyway.
517  }
518 }
std::unique_ptr< NotificationQueue< Func > > queue_
Definition: EventBase.h:734
event_base * evb_
Definition: EventBase.h:730
std::atomic< bool > stop_
Definition: EventBase.h:723
HHWheelTimer& folly::EventBase::timer ( )
inline

Definition at line 526 of file EventBase.h.

References folly::HHWheelTimer::newTimer().

Referenced by scheduleAt(), TEST_F(), and proxygen::WheelTimerInstance::WheelTimerInstance().

526  {
527  if (!wheelTimer_) {
529  }
530  return *wheelTimer_.get();
531  }
static UniquePtr newTimer(Args &&...args)
Definition: HHWheelTimer.h:61
HHWheelTimer::UniquePtr wheelTimer_
Definition: EventBase.h:709
void folly::EventBase::waitUntilRunning ( )

wait until the event loop starts (after starting the event loop thread).

Definition at line 249 of file EventBase.cpp.

References isRunning(), and folly::fibers::yield().

Referenced by folly::ScopedEventBaseThread::ScopedEventBaseThread(), proxygen::WorkerThread::start(), TEST(), and folly::ThreadWheelTimekeeper::ThreadWheelTimekeeper().

249  {
250  while (!isRunning()) {
252  }
253 }
bool isRunning() const
Definition: EventBase.h:487

Friends And Related Function Documentation

friend class detail::EventBaseLocalBase
friend

Definition at line 783 of file EventBase.h.

template<typename T >
friend class EventBaseLocal
friend

Definition at line 785 of file EventBase.h.

Member Data Documentation

SmoothLoopTime folly::EventBase::avgLoopTime_
private

Definition at line 744 of file EventBase.h.

Referenced by loopBody(), resetLoadAvg(), and setLoadAvgMsec().

const bool folly::EventBase::enableTimeMeasurement_
private

Definition at line 757 of file EventBase.h.

Referenced by bumpHandlingTime(), loopBody(), resetLoadAvg(), and setLoadAvgMsec().

event_base* folly::EventBase::evb_
private
ExecutionObserver* folly::EventBase::executionObserver_
private

Definition at line 774 of file EventBase.h.

std::unique_ptr<FunctionRunner> folly::EventBase::fnRunner_
private
bool folly::EventBase::invokingLoop_ {false}
private

Definition at line 767 of file EventBase.h.

Referenced by loopBody().

std::size_t folly::EventBase::latestLoopCnt_
private

Definition at line 761 of file EventBase.h.

Referenced by bumpHandlingTime(), and nothingHandledYet().

std::unordered_map<std::size_t, std::shared_ptr<void> > folly::EventBase::localStorage_
private
std::unordered_set<detail::EventBaseLocalBaseBase*> folly::EventBase::localStorageToDtor_
private
LoopCallbackList folly::EventBase::loopCallbacks_
private

Definition at line 711 of file EventBase.h.

Referenced by loopBody(), runInLoop(), and runLoopCallbacks().

bool folly::EventBase::loopKeepAliveActive_ {false}
private

Definition at line 738 of file EventBase.h.

Referenced by applyLoopKeepAlive(), and loopIgnoreKeepAlive().

ssize_t folly::EventBase::loopKeepAliveCount_ {0}
private

Definition at line 736 of file EventBase.h.

Referenced by loopForever(), and loopKeepAliveCount().

std::atomic<ssize_t> folly::EventBase::loopKeepAliveCountAtomic_ {0}
private

Definition at line 737 of file EventBase.h.

Referenced by loopKeepAliveCount().

std::atomic<std::thread::id> folly::EventBase::loopThread_
private

Definition at line 727 of file EventBase.h.

Referenced by checkIsInEventBaseThread(), loopBody(), and setName().

std::chrono::microseconds folly::EventBase::maxLatency_
private

Definition at line 741 of file EventBase.h.

Referenced by loopBody().

Func folly::EventBase::maxLatencyCob_
private

Definition at line 752 of file EventBase.h.

Referenced by loopBody().

SmoothLoopTime folly::EventBase::maxLatencyLoopTime_
private

Definition at line 749 of file EventBase.h.

Referenced by loopBody(), resetLoadAvg(), and setLoadAvgMsec().

std::string folly::EventBase::name_
private

Definition at line 777 of file EventBase.h.

Referenced by getName(), loopBody(), and setName().

std::size_t folly::EventBase::nextLoopCnt_
private

Definition at line 760 of file EventBase.h.

Referenced by bumpHandlingTime(), loopBody(), and nothingHandledYet().

std::shared_ptr<EventBaseObserver> folly::EventBase::observer_
private

Definition at line 770 of file EventBase.h.

Referenced by loopBody().

uint32_t folly::EventBase::observerSampleCount_
private

Definition at line 771 of file EventBase.h.

Referenced by loopBody().

LoopCallbackList folly::EventBase::onDestructionCallbacks_
private

Definition at line 713 of file EventBase.h.

Referenced by runOnDestruction(), and ~EventBase().

std::mutex folly::EventBase::onDestructionCallbacksMutex_
private

Definition at line 780 of file EventBase.h.

Referenced by runOnDestruction().

std::unique_ptr<NotificationQueue<Func> > folly::EventBase::queue_
private
LoopCallbackList folly::EventBase::runBeforeLoopCallbacks_
private

Definition at line 712 of file EventBase.h.

Referenced by loopBody(), runBeforeLoop(), and ~EventBase().

LoopCallbackList* folly::EventBase::runOnceCallbacks_
private

Definition at line 719 of file EventBase.h.

Referenced by runInLoop(), and runLoopCallbacks().

std::chrono::steady_clock::time_point folly::EventBase::startWork_
private

Definition at line 762 of file EventBase.h.

Referenced by bumpHandlingTime(), and loopBody().

std::atomic<bool> folly::EventBase::stop_
private

Definition at line 723 of file EventBase.h.

Referenced by loopBody(), and terminateLoopSoon().

std::unique_ptr<VirtualEventBase> folly::EventBase::virtualEventBase_
private

Definition at line 790 of file EventBase.h.

Referenced by applyLoopKeepAlive(), getVirtualEventBase(), and ~EventBase().

folly::once_flag folly::EventBase::virtualEventBaseInitFlag_
private

Definition at line 789 of file EventBase.h.

Referenced by getVirtualEventBase().

HHWheelTimer::UniquePtr folly::EventBase::wheelTimer_
private

Definition at line 709 of file EventBase.h.


The documentation for this class was generated from the following files: