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