]> git.apps.os.sepia.ceph.com Git - ceph-ci.git/commitdiff
common/thread: Fix race condition in make_named_thread
authorAdam C. Emerson <aemerson@redhat.com>
Tue, 22 Oct 2019 15:39:20 +0000 (11:39 -0400)
committerAdam C. Emerson <aemerson@redhat.com>
Wed, 23 Oct 2019 00:50:56 +0000 (20:50 -0400)
The thread may well no longer exist by the time we try to set the
name, so have the thread set its own name first thing.

Thanks to Ilya Dryomov <idryomov@gmail.com> for pointing it out.

Signed-off-by: Adam C. Emerson <aemerson@redhat.com>
src/common/Thread.h

index bc32755c30e887d517dd790a90321182214fa6d8..0ab65fca52f01a04abcda146393724d62f478985 100644 (file)
@@ -16,6 +16,8 @@
 #ifndef CEPH_THREAD_H
 #define CEPH_THREAD_H
 
+#include <functional>
+#include <string_view>
 #include <system_error>
 #include <thread>
 
@@ -68,13 +70,14 @@ std::string get_thread_name(const std::thread& t);
 void kill(std::thread& t, int signal);
 
 template<typename Fun, typename... Args>
-std::thread make_named_thread(const std::string& s,
+std::thread make_named_thread(std::string_view n,
                              Fun&& fun,
                              Args&& ...args) {
-  auto t = std::thread(std::forward<Fun>(fun),
-                      std::forward<Args>(args)...);
-  set_thread_name(t, s);
-  return t;
-}
 
+  return std::thread([n = std::string(n)](auto&& fun, auto&& ...args) {
+                      ceph_pthread_setname(pthread_self(), n.data());
+                      std::invoke(std::forward<Fun>(fun),
+                                  std::forward<Args>(args)...);
+                    }, std::forward<Fun>(fun), std::forward<Args>(args)...);
+}
 #endif