Add missing override and remove redundant virtual in folly
[folly.git] / folly / wangle / concurrent / test / ThreadPoolExecutorTest.cpp
index 596e27849c0dedbfb2cb34262766133d19d9fe8d..59c28c01c42d547e318ba599e41871fdfcb68178 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2014 Facebook, Inc.
+ * Copyright 2015 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@
 #include <glog/logging.h>
 #include <gtest/gtest.h>
 
+using namespace folly;
 using namespace folly::wangle;
 using namespace std::chrono;
 
@@ -309,12 +310,82 @@ TEST(ThreadPoolExecutorTest, PriorityPreemptionTest) {
   };
   CPUThreadPoolExecutor pool(0, 2);
   for (int i = 0; i < 50; i++) {
-    pool.add(lopri, 0);
+    pool.addWithPriority(lopri, Executor::LO_PRI);
   }
   for (int i = 0; i < 50; i++) {
-    pool.add(hipri, 1);
+    pool.addWithPriority(hipri, Executor::HI_PRI);
   }
   pool.setNumThreads(1);
   pool.join();
   EXPECT_EQ(100, completed);
 }
+
+class TestObserver : public ThreadPoolExecutor::Observer {
+ public:
+  void threadStarted(ThreadPoolExecutor::ThreadHandle*) override { threads_++; }
+  void threadStopped(ThreadPoolExecutor::ThreadHandle*) override { threads_--; }
+  void threadPreviouslyStarted(ThreadPoolExecutor::ThreadHandle*) override {
+    threads_++;
+  }
+  void threadNotYetStopped(ThreadPoolExecutor::ThreadHandle*) override {
+    threads_--;
+  }
+  void checkCalls() {
+    ASSERT_EQ(threads_, 0);
+  }
+ private:
+  std::atomic<int> threads_{0};
+};
+
+TEST(ThreadPoolExecutorTest, IOObserver) {
+  auto observer = std::make_shared<TestObserver>();
+
+  {
+    IOThreadPoolExecutor exe(10);
+    exe.addObserver(observer);
+    exe.setNumThreads(3);
+    exe.setNumThreads(0);
+    exe.setNumThreads(7);
+    exe.removeObserver(observer);
+    exe.setNumThreads(10);
+  }
+
+  observer->checkCalls();
+}
+
+TEST(ThreadPoolExecutorTest, CPUObserver) {
+  auto observer = std::make_shared<TestObserver>();
+
+  {
+    CPUThreadPoolExecutor exe(10);
+    exe.addObserver(observer);
+    exe.setNumThreads(3);
+    exe.setNumThreads(0);
+    exe.setNumThreads(7);
+    exe.removeObserver(observer);
+    exe.setNumThreads(10);
+  }
+
+  observer->checkCalls();
+}
+
+TEST(ThreadPoolExecutorTest, AddWithPriority) {
+  std::atomic_int c{0};
+  auto f = [&]{ c++; };
+
+  // IO exe doesn't support priorities
+  IOThreadPoolExecutor ioExe(10);
+  EXPECT_THROW(ioExe.addWithPriority(f, 0), std::runtime_error);
+
+  CPUThreadPoolExecutor cpuExe(10, 3);
+  cpuExe.addWithPriority(f, -1);
+  cpuExe.addWithPriority(f, 0);
+  cpuExe.addWithPriority(f, 1);
+  cpuExe.addWithPriority(f, -2); // will add at the lowest priority
+  cpuExe.addWithPriority(f, 2);  // will add at the highest priority
+  cpuExe.addWithPriority(f, Executor::LO_PRI);
+  cpuExe.addWithPriority(f, Executor::HI_PRI);
+  cpuExe.join();
+
+  EXPECT_EQ(7, c);
+}