ManualExecutor: add clear method
authorSven Over <over@fb.com>
Thu, 14 Jul 2016 15:13:31 +0000 (08:13 -0700)
committerFacebook Github Bot 8 <facebook-github-bot-8-bot@fb.com>
Thu, 14 Jul 2016 15:23:36 +0000 (08:23 -0700)
Summary:
ManualExecutor::clear removes all waiting functions from the
executor.

Reviewed By: yfeldblum

Differential Revision: D3555434

fbshipit-source-id: 604c352f2299b0dada062e5f8287be98e2a5f72c

folly/futures/ManualExecutor.h
folly/futures/test/ExecutorTest.cpp

index e84a0e01df47f1a1665285e2980e542a4b68e18a..1dfc5bb4fac9da619f4af9ac5bd190433c4f7b8f 100644 (file)
@@ -93,6 +93,21 @@ namespace folly {
 
     TimePoint now() override { return now_; }
 
+    /// Flush the function queue. Destroys all stored functions without
+    /// executing them. Returns number of removed functions.
+    std::size_t clear() {
+      std::queue<Func> funcs;
+      std::priority_queue<ScheduledFunc> scheduled_funcs;
+
+      {
+        std::lock_guard<std::mutex> lock(lock_);
+        funcs_.swap(funcs);
+        scheduledFuncs_.swap(scheduled_funcs);
+      }
+
+      return funcs.size() + scheduled_funcs.size();
+    }
+
    private:
     std::mutex lock_;
     std::queue<Func> funcs_;
index b29846a75ae3bbe6570f2ecc5282c90761b9be7f..3e7e72e593f79955cc3389e201c25e86b468d82e 100644 (file)
@@ -121,6 +121,19 @@ TEST(ManualExecutor, getViaDoesNotDeadlock) {
   t.join();
 }
 
+TEST(ManualExecutor, clear) {
+  ManualExecutor x;
+  size_t count = 0;
+  x.add([&] { ++count; });
+  x.scheduleAt([&] { ++count; }, x.now() + std::chrono::milliseconds(10));
+  EXPECT_EQ(0, count);
+
+  x.clear();
+  x.advance(std::chrono::milliseconds(10));
+  x.run();
+  EXPECT_EQ(0, count);
+}
+
 TEST(Executor, InlineExecutor) {
   InlineExecutor x;
   size_t counter = 0;