QueuedImmediateExecutor tweaks
authorYedidya Feldblum <yfeldblum@fb.com>
Thu, 23 Nov 2017 19:59:32 +0000 (11:59 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 23 Nov 2017 20:05:14 +0000 (12:05 -0800)
Summary:
[Folly] `QueuedImmediateExecutor` tweaks.

* Add a leaky meyers singleton instance.
* Make the thread-local queue an instance variable. Callers which want the singleton thread-local queue can use the singleton executor instance instance, for the same effect.
* Simplify the body of `add`, and perform the thread-local lookup only once per invocation.

Reviewed By: djwatson

Differential Revision: D6399067

fbshipit-source-id: 03904885a70c4b943141bd83868414d27232fd6a

folly/executors/QueuedImmediateExecutor.cpp
folly/executors/QueuedImmediateExecutor.h

index a8a9d0a8407f29f3f6c23a4ee6a9f27ce09fc16e..676d26ebd974d392d3679c679357b19ff7fcf9a1 100644 (file)
  */
 
 #include <folly/executors/QueuedImmediateExecutor.h>
-#include <folly/ThreadLocal.h>
-#include <queue>
+
+#include <folly/Indestructible.h>
 
 namespace folly {
 
-void QueuedImmediateExecutor::addStatic(Func callback) {
-  static folly::ThreadLocal<std::queue<Func>> q_;
+QueuedImmediateExecutor& QueuedImmediateExecutor::instance() {
+  static auto instance = Indestructible<QueuedImmediateExecutor>{};
+  return *instance;
+}
 
-  if (q_->empty()) {
-    q_->push(std::move(callback));
-    while (!q_->empty()) {
-      q_->front()();
-      q_->pop();
+void QueuedImmediateExecutor::add(Func callback) {
+  auto& q = *q_;
+  q.push(std::move(callback));
+  if (q.size() == 1) {
+    while (!q.empty()) {
+      q.front()();
+      q.pop();
     }
-  } else {
-    q_->push(std::move(callback));
   }
 }
 
index b98047a04e0d0cd891557386ce3adbccbde549f7..176c2532ff0ab99a5f6ebbd9ff9888bd2acfc3a3 100644 (file)
 
 #pragma once
 
+#include <queue>
+
 #include <folly/Executor.h>
+#include <folly/ThreadLocal.h>
 
 namespace folly {
 
@@ -27,13 +30,12 @@ namespace folly {
  */
 class QueuedImmediateExecutor : public Executor {
  public:
-  /// There's really only one queue per thread, no matter how many
-  /// QueuedImmediateExecutor objects you may have.
-  static void addStatic(Func);
+  static QueuedImmediateExecutor& instance();
+
+  void add(Func func) override;
 
-  void add(Func func) override {
-    addStatic(std::move(func));
-  }
+ private:
+  folly::ThreadLocal<std::queue<Func>> q_;
 };
 
 } // namespace folly