]> git.ipfire.org Git - thirdparty/binutils-gdb.git/commitdiff
[gdbsupport] Add thread_pool::id
authorTom de Vries <tdevries@suse.de>
Fri, 15 Jul 2022 09:20:13 +0000 (11:20 +0200)
committerTom de Vries <tdevries@suse.de>
Thu, 21 Jul 2022 13:06:39 +0000 (15:06 +0200)
Used to implement a poor mans thread_local.

gdbsupport/thread-pool.cc
gdbsupport/thread-pool.h

index ddb76b691c1bc9cc01773b6bff7f9637f5016fd7..c102aec7872276b0f0ce958de9d0c3b8cae4d967 100644 (file)
@@ -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<std::mutex> 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 ();
     }
 
index 4db35bab957b332e7817417b6290ff0521c6df6c..788f189b2b7ea843399f89bf22a3d58db30c080a 100644 (file)
@@ -22,6 +22,7 @@
 
 #include <queue>
 #include <vector>
+#include <unordered_map>
 #include <functional>
 #if CXX_STD_THREAD
 #include <thread>
@@ -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<void> post_task (std::function<void ()> &&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<std::thread::id, unsigned> m_thread_ids;
+  std::unordered_map<unsigned, std::thread::id> m_thread_ids_reverse;
 #endif /* CXX_STD_THREAD */
 };