parallel-for.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* Parallel for loops
  2. Copyright (C) 2019-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #ifndef GDBSUPPORT_PARALLEL_FOR_H
  15. #define GDBSUPPORT_PARALLEL_FOR_H
  16. #include <algorithm>
  17. #if CXX_STD_THREAD
  18. #include <thread>
  19. #include "gdbsupport/thread-pool.h"
  20. #endif
  21. namespace gdb
  22. {
  23. /* A very simple "parallel for". This splits the range of iterators
  24. into subranges, and then passes each subrange to the callback. The
  25. work may or may not be done in separate threads.
  26. This approach was chosen over having the callback work on single
  27. items because it makes it simple for the caller to do
  28. once-per-subrange initialization and destruction. */
  29. template<class RandomIt, class RangeFunction>
  30. void
  31. parallel_for_each (RandomIt first, RandomIt last, RangeFunction callback)
  32. {
  33. #if CXX_STD_THREAD
  34. /* So we can use a local array below. */
  35. const size_t local_max = 16;
  36. size_t n_threads = std::min (thread_pool::g_thread_pool->thread_count (),
  37. local_max);
  38. size_t n_actual_threads = 0;
  39. std::future<void> futures[local_max];
  40. size_t n_elements = last - first;
  41. if (n_threads > 1)
  42. {
  43. /* Arbitrarily require that there should be at least 10 elements
  44. in a thread. */
  45. if (n_elements / n_threads < 10)
  46. n_threads = std::max (n_elements / 10, (size_t) 1);
  47. size_t elts_per_thread = n_elements / n_threads;
  48. n_actual_threads = n_threads - 1;
  49. for (int i = 0; i < n_actual_threads; ++i)
  50. {
  51. RandomIt end = first + elts_per_thread;
  52. auto task = [=] ()
  53. {
  54. callback (first, end);
  55. };
  56. futures[i] = gdb::thread_pool::g_thread_pool->post_task (task);
  57. first = end;
  58. }
  59. }
  60. #endif /* CXX_STD_THREAD */
  61. /* Process all the remaining elements in the main thread. */
  62. callback (first, last);
  63. #if CXX_STD_THREAD
  64. for (int i = 0; i < n_actual_threads; ++i)
  65. futures[i].wait ();
  66. #endif /* CXX_STD_THREAD */
  67. }
  68. }
  69. #endif /* GDBSUPPORT_PARALLEL_FOR_H */