From 5b60c98769ba297053801a3192187ebdd558698a Mon Sep 17 00:00:00 2001 From: Pau Espin Pedrol Date: Thu, 20 Sep 2018 18:04:46 +0200 Subject: Use pthread_setname_np to name threads osmo-trx can start a considerable amount of threads that can make debugging it challenging at least. By using phtread_setname_np, the system sets a meaningful name to the thread which can be seen while debugging with gdb or by printing /proc/$pid/task/$tid/comm. Now we also log system TID when setting the name so we can identify different tasks in /proc even if pthread_setname_np fails. Change-Id: I84711739c3e224cb383fd12b6db933785b28209e --- CommonLibs/Threads.cpp | 23 +++++++++++++++++++++-- CommonLibs/Threads.h | 2 ++ 2 files changed, 23 insertions(+), 2 deletions(-) (limited to 'CommonLibs') diff --git a/CommonLibs/Threads.cpp b/CommonLibs/Threads.cpp index de6520b..2988e12 100644 --- a/CommonLibs/Threads.cpp +++ b/CommonLibs/Threads.cpp @@ -24,11 +24,17 @@ */ - - +#include +#include #include "Threads.h" #include "Timeval.h" +#include "Logger.h" + +#ifndef gettid +#include +#define gettid() syscall(SYS_gettid) +#endif using namespace std; @@ -102,6 +108,19 @@ void Signal::wait(Mutex& wMutex, unsigned timeout) const pthread_cond_timedwait(&mSignal,&wMutex.mMutex,&waitTime); } +void set_selfthread_name(const char *name) +{ + pthread_t selfid = pthread_self(); + pid_t tid = gettid(); + if (pthread_setname_np(selfid, name) == 0) { + LOG(INFO) << "Thread "<< selfid << " (task " << tid << ") set name: " << name; + } else { + char buf[256]; + int err = errno; + char* err_str = strerror_r(err, buf, sizeof(buf)); + LOG(NOTICE) << "Thread "<< selfid << " (task " << tid << ") set name \"" << name << "\" failed: (" << err << ") " << err_str; + } +} void Thread::start(void *(*task)(void*), void *arg) { diff --git a/CommonLibs/Threads.h b/CommonLibs/Threads.h index 47c7275..857c5d9 100644 --- a/CommonLibs/Threads.h +++ b/CommonLibs/Threads.h @@ -141,6 +141,8 @@ class Signal { #define START_THREAD(thread,function,argument) \ thread.start((void *(*)(void*))function, (void*)argument); +void set_selfthread_name(const char *name); + /** A C++ wrapper for pthread threads. */ class Thread { -- cgit v1.2.3