HHWheelTimer - fix scheduling timeouts within callbacks
[folly.git] / folly / io / async / HHWheelTimer.h
index 36a7d0f2a5badcd6451bb7ed17f17cdf77387c2e..c0c1f8bf8865ea393dd173823133fe06d2fb2aef 100644 (file)
@@ -54,7 +54,7 @@ namespace folly {
  * maintaining time and timers, provided that we can maintain
  * a consistent rate of ticks.
  */
-class HHWheelTimer : protected folly::AsyncTimeout,
+class HHWheelTimer : private folly::AsyncTimeout,
                      public folly::DelayedDestruction {
  public:
   typedef std::unique_ptr<HHWheelTimer, Destructor> UniquePtr;
@@ -95,6 +95,16 @@ class HHWheelTimer : protected folly::AsyncTimeout,
       return wheel_ != nullptr;
     }
 
+   protected:
+    /**
+     * Don't override this unless you're doing a test. This is mainly here so
+     * that we can override it to simulate lag in steady_clock.
+     */
+    virtual std::chrono::milliseconds getCurTime() {
+      return std::chrono::duration_cast<std::chrono::milliseconds>(
+        std::chrono::steady_clock::now().time_since_epoch());
+    }
+
    private:
     // Get the time remaining until this timeout expires
     std::chrono::milliseconds getTimeRemaining(
@@ -187,6 +197,10 @@ class HHWheelTimer : protected folly::AsyncTimeout,
     catchupEveryN_ = everyN;
   }
 
+  bool isDetachable() const {
+    return !folly::AsyncTimeout::isScheduled();
+  }
+
   using folly::AsyncTimeout::attachEventBase;
   using folly::AsyncTimeout::detachEventBase;
   using folly::AsyncTimeout::getTimeoutManager;
@@ -219,7 +233,7 @@ class HHWheelTimer : protected folly::AsyncTimeout,
   typedef Callback::List CallbackList;
   CallbackList buckets_[WHEEL_BUCKETS][WHEEL_SIZE];
 
-  uint32_t timeToWheelTicks(std::chrono::milliseconds t) {
+  int64_t timeToWheelTicks(std::chrono::milliseconds t) {
     return t.count() / interval_.count();
   }
 
@@ -232,6 +246,7 @@ class HHWheelTimer : protected folly::AsyncTimeout,
 
   uint32_t catchupEveryN_;
   uint32_t expirationsSinceCatchup_;
+  bool processingCallbacksGuard_;
 };
 
 } // folly