Introduce destruction callbacks
[folly.git] / folly / io / async / EventBase.cpp
index 130ba5fbc2b21be360ddb7b598434cf6548618a8..ab34b7c3f93366343bee6bffc3e3982821ff2c2c 100644 (file)
@@ -178,6 +178,13 @@ EventBase::EventBase(event_base* evb)
 }
 
 EventBase::~EventBase() {
+  // Call all destruction callbacks, before we start cleaning up our state.
+  while (!onDestructionCallbacks_.empty()) {
+    LoopCallback* callback = &onDestructionCallbacks_.front();
+    onDestructionCallbacks_.pop_front();
+    callback->runLoopCallback();
+  }
+
   // Delete any unfired CobTimeout objects, so that we don't leak memory
   // (Note that we don't fire them.  The caller is responsible for cleaning up
   // its own data structures if it destroys the EventBase with unfired events
@@ -445,6 +452,12 @@ void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
   }
 }
 
+void EventBase::runOnDestruction(LoopCallback* callback) {
+  DCHECK(isInEventBaseThread());
+  callback->cancelLoopCallback();
+  onDestructionCallbacks_.push_back(*callback);
+}
+
 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
   // Send the message.
   // It will be received by the FunctionRunner in the EventBase's thread.