From 947a1585216b0ff01bde184bccb1231626e86b57 Mon Sep 17 00:00:00 2001 From: Tom de Vries Date: Fri, 15 Jul 2022 11:20:13 +0200 Subject: [gdbsupport] Add thread_pool::id Used to implement a poor mans thread_local. --- gdbsupport/thread-pool.cc | 22 +++++++++++++++++++++- gdbsupport/thread-pool.h | 5 +++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/gdbsupport/thread-pool.cc b/gdbsupport/thread-pool.cc index ddb76b69..c102aec 100644 --- a/gdbsupport/thread-pool.cc +++ b/gdbsupport/thread-pool.cc @@ -149,12 +149,25 @@ thread_pool::~thread_pool () case -- see the comment by the definition of g_thread_pool. */ } +unsigned thread_pool::id () +{ +#if CXX_STD_THREAD + std::thread::id id = std::this_thread::get_id(); + return g_thread_pool->m_thread_ids[id]; +#else + return 0; +#endif +} + void thread_pool::set_thread_count (size_t num_threads) { #if CXX_STD_THREAD std::lock_guard guard (m_tasks_mutex); + m_thread_ids[std::this_thread::get_id ()] = 0; + m_thread_ids_reverse[0] = std::this_thread::get_id (); + /* If the new size is larger, start some new threads. */ if (m_thread_count < num_threads) { @@ -166,6 +179,8 @@ thread_pool::set_thread_count (size_t num_threads) try { std::thread thread (&thread_pool::thread_function, this); + m_thread_ids[thread.get_id ()] = i + 1; + m_thread_ids_reverse[i + 1] = thread.get_id (); thread.detach (); } catch (const std::system_error &) @@ -182,7 +197,12 @@ thread_pool::set_thread_count (size_t num_threads) if (num_threads < m_thread_count) { for (size_t i = num_threads; i < m_thread_count; ++i) - m_tasks.emplace (); + { + std::thread::id id = m_thread_ids_reverse[i]; + m_thread_ids.erase (id); + m_thread_ids_reverse.erase (i); + m_tasks.emplace (); + } m_tasks_cv.notify_all (); } diff --git a/gdbsupport/thread-pool.h b/gdbsupport/thread-pool.h index 4db35ba..788f189 100644 --- a/gdbsupport/thread-pool.h +++ b/gdbsupport/thread-pool.h @@ -22,6 +22,7 @@ #include #include +#include #include #if CXX_STD_THREAD #include @@ -119,6 +120,8 @@ public: #endif } + static unsigned id (); + /* Post a task to the thread pool. A future is returned, which can be used to wait for the result. */ future post_task (std::function &&func) @@ -177,6 +180,8 @@ private: between the main thread and the worker threads. */ std::condition_variable m_tasks_cv; std::mutex m_tasks_mutex; + std::unordered_map m_thread_ids; + std::unordered_map m_thread_ids_reverse; #endif /* CXX_STD_THREAD */ }; -- cgit v1.1