diff --git a/ddprof-lib/src/main/cpp/profiler.cpp b/ddprof-lib/src/main/cpp/profiler.cpp index 06b5d16fb4..7399635cbf 100644 --- a/ddprof-lib/src/main/cpp/profiler.cpp +++ b/ddprof-lib/src/main/cpp/profiler.cpp @@ -996,21 +996,21 @@ void Profiler::updateJavaThreadNames() { } void Profiler::updateNativeThreadNames() { - ThreadList *thread_list = OS::listThreads(); - for (int tid; (tid = thread_list->next()) != -1;) { - _thread_info.updateThreadName( - tid, [](int tid) -> std::unique_ptr { - const size_t buffer_size = 64; - char *name_buf = new char[buffer_size]; - if (OS::threadName(tid, name_buf, buffer_size)) { - return std::unique_ptr(name_buf); - } - delete[] name_buf; - return nullptr; - }); - } + ThreadList *thread_list = OS::listThreads(); + constexpr size_t buffer_size = 64; + char name_buf[buffer_size]; // Stack-allocated buffer + + for (int tid; (tid = thread_list->next()) != -1;) { + _thread_info.updateThreadName( + tid, [&](int tid) -> std::string { + if (OS::threadName(tid, name_buf, buffer_size)) { + return std::string(name_buf, buffer_size); + } + return std::string(); + }); + } - delete thread_list; + delete thread_list; } Engine *Profiler::selectCpuEngine(Arguments &args) { diff --git a/ddprof-lib/src/main/cpp/threadInfo.cpp b/ddprof-lib/src/main/cpp/threadInfo.cpp index 0ca6a906b4..10299b628c 100644 --- a/ddprof-lib/src/main/cpp/threadInfo.cpp +++ b/ddprof-lib/src/main/cpp/threadInfo.cpp @@ -67,17 +67,16 @@ int ThreadInfo::size() { } void ThreadInfo::updateThreadName( - int tid, std::function(int)> resolver) { - MutexLocker ml(_ti_lock); - - std::map::iterator it = _thread_names.lower_bound(tid); - if (it == _thread_names.end() || it->first != tid) { - std::unique_ptr namePtr = resolver(tid); - if (namePtr.get() != nullptr) { - _thread_names.insert(it, std::map::value_type( - tid, static_cast(namePtr.get()))); + int tid, std::function resolver) { + MutexLocker ml(_ti_lock); + auto it = _thread_names.find(tid); + if (it == _thread_names.end()) { + // Thread ID not found, insert new entry + std::string name = resolver(tid); + if (!name.empty()) { + _thread_names.emplace(tid, std::move(name)); + } } - } } void ThreadInfo::reportCounters() { diff --git a/ddprof-lib/src/main/cpp/threadInfo.h b/ddprof-lib/src/main/cpp/threadInfo.h index 5834a3cd04..9fab8d2f5f 100644 --- a/ddprof-lib/src/main/cpp/threadInfo.h +++ b/ddprof-lib/src/main/cpp/threadInfo.h @@ -22,8 +22,7 @@ class ThreadInfo { void set(int tid, const char *name, u64 java_thread_id); std::pair, u64> get(int tid); - void updateThreadName(int threadId, - std::function(int)> resolver); + void updateThreadName(int tid, std::function resolver); int size();