ThreadedRepeatingFunctionRunner: Name all the threads
authorAlexey Spiridonov <lesha@fb.com>
Wed, 17 May 2017 22:56:39 +0000 (15:56 -0700)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Wed, 17 May 2017 23:05:58 +0000 (16:05 -0700)
Summary: Name all repeating function threads for ease of debugging.

Reviewed By: yfeldblum

Differential Revision: D5065281

fbshipit-source-id: e875e654dfa644a265e44416baf5fbf23c9da434

folly/experimental/ThreadedRepeatingFunctionRunner.cpp
folly/experimental/ThreadedRepeatingFunctionRunner.h
folly/experimental/test/ThreadedRepeatingFunctionRunnerTest.cpp

index a309f01ad826aca1ed4b34723069dab6bb4b19a3..82ab4081a09caeb2147483da713cee8c5becd499 100644 (file)
@@ -15,6 +15,7 @@
  */
 #include "folly/experimental/ThreadedRepeatingFunctionRunner.h"
 
+#include <folly/ThreadName.h>
 #include <glog/logging.h>
 #include <iostream>
 
@@ -53,13 +54,18 @@ bool ThreadedRepeatingFunctionRunner::stopImpl() {
 }
 
 void ThreadedRepeatingFunctionRunner::add(
+    std::string name,
     RepeatingFn fn,
     std::chrono::milliseconds initialSleep) {
-  threads_.emplace_back(
-      &ThreadedRepeatingFunctionRunner::executeInLoop,
-      this,
-      std::move(fn),
-      initialSleep);
+  threads_.emplace_back([
+    name = std::move(name),
+    fn = std::move(fn),
+    initialSleep,
+    this
+  ]() mutable {
+    setThreadName(name);
+    executeInLoop(std::move(fn), initialSleep);
+  });
 }
 
 bool ThreadedRepeatingFunctionRunner::waitFor(
index 75122dae986a9c63a81bbe9bcfafdbd48abb4876..52c7461b44844c5b81b6038a2a1a560709aad6f5 100644 (file)
@@ -120,7 +120,8 @@ class ThreadedRepeatingFunctionRunner final {
   /**
    * Run your noexcept function `f` in a background loop, sleeping between
    * calls for a duration returned by `f`.  Optionally waits for
-   * `initialSleep` before calling `f` for the first time.
+   * `initialSleep` before calling `f` for the first time.  Names the thread
+   * using up to the first 15 chars of `name`.
    *
    * DANGER: If a non-final class has a ThreadedRepeatingFunctionRunner
    * member (which, by the way, must be declared last in the class), then
@@ -130,6 +131,7 @@ class ThreadedRepeatingFunctionRunner final {
    * your threads.
    */
   void add(
+      std::string name,
       RepeatingFn f,
       std::chrono::milliseconds initialSleep = std::chrono::milliseconds(0));
 
index 28c79f399ada243d26c6584a0f8a058ec5ca1794..41d6e243d6fb6f615dcd7589137601b4199ca68d 100644 (file)
@@ -27,7 +27,7 @@ struct Foo {
   }
 
   void start() {
-    runner_.add([this]() {
+    runner_.add("Foo", [this]() {
       ++data;
       return std::chrono::seconds(0);
     });
@@ -45,7 +45,7 @@ struct FooLongSleep {
   }
 
   void start() {
-    runner_.add([this]() {
+    runner_.add("FooLongSleep", [this]() {
       data.store(1);
       return 1000h; // Test would time out if we waited
     });