From 6e98d33ce72d53fb5b2d113ccc7720897110b654 Mon Sep 17 00:00:00 2001 From: "Adam C. Emerson" Date: Tue, 16 Feb 2016 14:43:51 -0500 Subject: [PATCH] common: Add make_named_thread To allow us to make a std::thread with a name. Signed-off-by: Adam C. Emerson --- src/common/Thread.cc | 32 +++++++++++++++++++++++++++++++- src/common/Thread.h | 23 ++++++++++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/common/Thread.cc b/src/common/Thread.cc index a58c7ba252cce..827443a13ee16 100644 --- a/src/common/Thread.cc +++ b/src/common/Thread.cc @@ -12,7 +12,8 @@ * */ -#include "include/compat.h" +#include + #include "common/Thread.h" #include "common/code_environment.h" #include "common/debug.h" @@ -198,3 +199,32 @@ int Thread::set_affinity(int id) r = _set_affinity(id); return r; } + +// Functions for std::thread +// ========================= + +void set_thread_name(std::thread& t, const std::string& s) { + int r = ceph_pthread_setname(t.native_handle(), s.c_str()); + if (r != 0) { + throw std::system_error(r, std::generic_category()); + } +} +std::string get_thread_name(const std::thread& t) { + std::string s(256, '\0'); + + int r = ceph_pthread_getname(const_cast(t).native_handle(), + s.data(), s.length()); + if (r != 0) { + throw std::system_error(r, std::generic_category()); + } + s.resize(std::strlen(s.data())); + return s; +} + +void kill(std::thread& t, int signal) +{ + auto r = pthread_kill(t.native_handle(), signal); + if (r != 0) { + throw std::system_error(r, std::generic_category()); + } +} diff --git a/src/common/Thread.h b/src/common/Thread.h index 54fd750925fe7..8e7cadd14c3bd 100644 --- a/src/common/Thread.h +++ b/src/common/Thread.h @@ -1,4 +1,4 @@ - // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- +// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system @@ -16,9 +16,14 @@ #ifndef CEPH_THREAD_H #define CEPH_THREAD_H +#include +#include + #include #include +#include "include/compat.h" + class Thread { private: pthread_t thread_id; @@ -56,4 +61,20 @@ class Thread { int set_affinity(int cpuid); }; +// Functions for with std::thread + +void set_thread_name(std::thread& t, const std::string& s); +std::string get_thread_name(const std::thread& t); +void kill(std::thread& t, int signal); + +template +std::thread make_named_thread(const std::string& s, + Fun&& fun, + Args&& ...args) { + auto t = std::thread(std::forward(fun), + std::forward(args)...); + set_thread_name(t, s); + return t; +} + #endif -- 2.39.5