From a4596d1c2f627e4568eb6c01d81b6e45f488715a Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 21 Jul 2016 02:50:56 +0300 Subject: [PATCH] Add an interface for naming threads --- source/core/thread.cpp | 4 +++- source/core/thread.h | 8 +++++++- source/core/unix/thread.cpp | 6 ++++++ source/core/windows/thread.cpp | 5 +++++ 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/source/core/thread.cpp b/source/core/thread.cpp index d2451a0..721e8cf 100644 --- a/source/core/thread.cpp +++ b/source/core/thread.cpp @@ -6,8 +6,9 @@ using namespace std; namespace Msp { -Thread::Thread(): +Thread::Thread(const string &name): priv_(new Private), + name_(name), state_(PENDING) { } @@ -48,6 +49,7 @@ void Thread::launch() ThreadReturn THREAD_CALL Thread::Private::main_wrapper(void *arg) { Thread *thread = reinterpret_cast(arg); + thread->platform_setname(); thread->main(); thread->state_ = FINISHED; return 0; diff --git a/source/core/thread.h b/source/core/thread.h index 1fff362..7cf17b8 100644 --- a/source/core/thread.h +++ b/source/core/thread.h @@ -1,6 +1,8 @@ #ifndef MSP_CORE_THREAD_H_ #define MSP_CORE_THREAD_H_ +#include + namespace Msp { /** @@ -25,16 +27,19 @@ private: }; Private *priv_; + std::string name_; State state_; protected: - Thread(); + Thread(const std::string & = std::string()); private: Thread(const Thread &); Thread &operator=(const Thread &); public: virtual ~Thread(); + const std::string &get_name() const { return name_; } + /** Indicates whether the thread has finished running. */ bool is_finished() { return state_>=FINISHED; } @@ -54,6 +59,7 @@ private: void platform_join(); void platform_kill(); void platform_launch(); + void platform_setname(); protected: virtual void main() = 0; diff --git a/source/core/unix/thread.cpp b/source/core/unix/thread.cpp index 26afeef..3c17a9a 100644 --- a/source/core/unix/thread.cpp +++ b/source/core/unix/thread.cpp @@ -20,4 +20,10 @@ void Thread::platform_launch() pthread_create(&priv_->handle, 0, &Private::main_wrapper, this); } +void Thread::platform_setname() +{ + if(!name_.empty()) + pthread_setname_np(priv_->handle, name_.c_str()); +} + } // namespace Msp diff --git a/source/core/windows/thread.cpp b/source/core/windows/thread.cpp index 7c43618..ab02c4d 100644 --- a/source/core/windows/thread.cpp +++ b/source/core/windows/thread.cpp @@ -20,4 +20,9 @@ void Thread::platform_launch() priv_->handle = CreateThread(0, 0, &Private::main_wrapper, this, 0, &dummy); } +void Thread::platform_setname() +{ + // TODO: https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx +} + } // namespace Msp -- 2.43.0