From 6a4d2250928e77c0d883e333179e6d5ef98ad9fb Mon Sep 17 00:00:00 2001 From: Perttu Ahola Date: Mon, 27 Oct 2014 12:59:16 +0200 Subject: [PATCH] interface/thread,thread_pool: Allow setting thread name --- src/impl/thread.cpp | 25 ++++++++++++++++++++++--- src/impl/thread_pool.cpp | 6 +++++- src/interface/thread.h | 1 + 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/impl/thread.cpp b/src/impl/thread.cpp index b8dddf8..92b62a5 100644 --- a/src/impl/thread.cpp +++ b/src/impl/thread.cpp @@ -22,6 +22,7 @@ struct CThread: public Thread bool m_running = false; bool m_stop_requested = false; interface::Mutex m_mutex; // Protects each of the former variables + ss_ m_name = "unknown"; // Read-only when thread is running (no mutex) up_ m_thing; pthread_t m_thread; @@ -37,15 +38,25 @@ struct CThread: public Thread static void* run_thread(void *arg) { - log_d(MODULE, "Thread %p start", arg); + CThread *thread = (CThread*)arg; + log_d(MODULE, "Thread started: %p (%s)", thread, cs(thread->m_name)); + + // Set name + if(!thread->m_name.empty()){ + ss_ limited_name = thread->m_name.size() <= 15 ? + thread->m_name : thread->m_name.substr(0, 15); + if(pthread_setname_np(thread->m_thread, limited_name.c_str())){ + log_w(MODULE, "Failed to set thread name (thread %p, name \"%s\")", + thread, limited_name.c_str()); + } + } + #ifndef _WIN32 // Disable all signals sigset_t sigset; sigemptyset(&sigset); (void)pthread_sigmask(SIG_SETMASK, &sigset, NULL); #endif - // Go on - CThread *thread = (CThread*)arg; try { if(thread->m_thing) @@ -63,6 +74,14 @@ struct CThread: public Thread // Interface + void set_name(const ss_ &name) + { + interface::MutexScope ms(m_mutex); + if(m_running) + throw Exception("Cannot set name of running thread"); + m_name = name; + } + void start() { interface::MutexScope ms(m_mutex); diff --git a/src/impl/thread_pool.cpp b/src/impl/thread_pool.cpp index ef6ce89..0b091f9 100644 --- a/src/impl/thread_pool.cpp +++ b/src/impl/thread_pool.cpp @@ -45,7 +45,12 @@ struct CThreadPool: public ThreadPool static void* run_thread(void *arg) { + Thread *thread = (Thread*)arg; log_d(MODULE, "Worker thread %p start", arg); + // Set name + if(pthread_setname_np(thread->thread, "buildat:worker")){ + log_w(MODULE, "Failed to set worker thread %p name", thread); + } #ifndef _WIN32 // Disable all signals sigset_t sigset; @@ -53,7 +58,6 @@ struct CThreadPool: public ThreadPool (void)pthread_sigmask(SIG_SETMASK, &sigset, NULL); #endif // Go on - Thread *thread = (Thread*)arg; for(;;){ // Wait for a task thread->pool->m_tasks_sem.wait(); diff --git a/src/interface/thread.h b/src/interface/thread.h index ea9f3d4..7083ff8 100644 --- a/src/interface/thread.h +++ b/src/interface/thread.h @@ -17,6 +17,7 @@ namespace interface struct Thread { virtual ~Thread(){} + virtual void set_name(const ss_ &name) = 0; // Useful for debugging virtual void start() = 0; virtual bool is_running() = 0; virtual void request_stop() = 0;