FunctionScheduler - return whether shutdown was successful
authorMirek Klimos <miro@fb.com>
Fri, 7 Oct 2016 18:18:57 +0000 (11:18 -0700)
committerFacebook Github Bot <facebook-github-bot-bot@fb.com>
Fri, 7 Oct 2016 18:23:33 +0000 (11:23 -0700)
Summary: We want to fail fast if we attempt to stop a scheduler that was not running

Reviewed By: yfeldblum

Differential Revision: D3976919

fbshipit-source-id: d8aa8b35aa9e22758e6a7ef64f48a7dd6d990b1c

folly/experimental/FunctionScheduler.cpp
folly/experimental/FunctionScheduler.h
folly/experimental/test/FunctionSchedulerTest.cpp

index 6727ca35f8ab8e6ee0ad378a10e0f3dd8aeece0d..2e0ee6ebea9c78f24d0b908548f09e50ecd900f1 100644 (file)
@@ -277,17 +277,18 @@ bool FunctionScheduler::start() {
   return true;
 }
 
-void FunctionScheduler::shutdown() {
+bool FunctionScheduler::shutdown() {
   {
     std::lock_guard<std::mutex> g(mutex_);
     if (!running_) {
-      return;
+      return false;
     }
 
     running_ = false;
     runningCondvar_.notify_one();
   }
   thread_.join();
+  return true;
 }
 
 void FunctionScheduler::run() {
index e5514596c0a6c1afdba58d28447e4812140e9576..1668c501e6aef35d6086b51660aa25257c7aaa70 100644 (file)
@@ -177,8 +177,9 @@ class FunctionScheduler {
    * Stops the FunctionScheduler.
    *
    * It may be restarted later by calling start() again.
+   * Returns false if the scheduler was not running.
    */
-  void shutdown();
+  bool shutdown();
 
   /**
    * Set the name of the worker thread.
index e54d1b4abfb9a0a851026c7a6f5eb467304c2920..eb122d6f10f9eb83c9dee5de1dd809e8bdb7e303 100644 (file)
@@ -50,6 +50,19 @@ void delay(int n) {
 
 } // unnamed namespace
 
+TEST(FunctionScheduler, StartAndShutdown) {
+  FunctionScheduler fs;
+  EXPECT_TRUE(fs.start());
+  EXPECT_FALSE(fs.start());
+  EXPECT_TRUE(fs.shutdown());
+  EXPECT_FALSE(fs.shutdown());
+  // start again
+  EXPECT_TRUE(fs.start());
+  EXPECT_FALSE(fs.start());
+  EXPECT_TRUE(fs.shutdown());
+  EXPECT_FALSE(fs.shutdown());
+}
+
 TEST(FunctionScheduler, SimpleAdd) {
   int total = 0;
   FunctionScheduler fs;
@@ -76,7 +89,6 @@ TEST(FunctionScheduler, AddCancel) {
   delay(2);
   EXPECT_EQ(4, total);
   fs.addFunction([&] { total += 1; }, testInterval(2), "add2");
-  EXPECT_FALSE(fs.start()); // already running
   delay(1);
   EXPECT_EQ(5, total);
   delay(2);