1 /* Self tests for parallel_for_each
3 Copyright (C) 2021-2024 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 /* This file is divided in two parts:
21 - FOR_EACH-undefined, and
23 The former includes the latter, more than once, with different values for
24 FOR_EACH. The FOR_EACH-defined part reads like a regular function. */
27 #include "gdbsupport/selftest.h"
28 #include "gdbsupport/parallel-for.h"
32 #include "gdbsupport/thread-pool.h"
35 namespace parallel_for
{
37 struct save_restore_n_threads
39 save_restore_n_threads ()
40 : n_threads (gdb::thread_pool::g_thread_pool
->thread_count ())
44 ~save_restore_n_threads ()
46 gdb::thread_pool::g_thread_pool
->set_thread_count (n_threads
);
52 /* Define test_par using TEST in the FOR_EACH-defined part. */
54 #define FOR_EACH gdb::parallel_for_each
55 #include "parallel-for-selftests.c"
59 /* Define test_seq using TEST in the FOR_EACH-defined part. */
61 #define FOR_EACH gdb::sequential_for_each
62 #include "parallel-for-selftests.c"
84 #endif /* CXX_STD_THREAD */
86 void _initialize_parallel_for_selftests ();
88 _initialize_parallel_for_selftests ()
91 selftests::register_test ("parallel_for",
92 selftests::parallel_for::test_n_threads
);
93 #endif /* CXX_STD_THREAD */
101 save_restore_n_threads saver
;
102 gdb::thread_pool::g_thread_pool
->set_thread_count (n_threads
);
106 std::atomic
<int> counter (0);
107 FOR_EACH (1, 0, NUMBER
,
108 [&] (int start
, int end
)
110 counter
+= end
- start
;
112 SELF_CHECK (counter
== NUMBER
);
116 [&] (int start
, int end
)
118 counter
+= end
- start
;
120 SELF_CHECK (counter
== 0);
124 /* Check that if there are fewer tasks than threads, then we won't
125 end up with a null result. */
126 std::vector
<std::unique_ptr
<int>> intresults
;
127 std::atomic
<bool> any_empty_tasks (false);
130 [&] (int start
, int end
)
133 any_empty_tasks
= true;
134 return std::make_unique
<int> (end
- start
);
136 SELF_CHECK (!any_empty_tasks
);
137 SELF_CHECK (std::all_of (intresults
.begin (),
139 [] (const std::unique_ptr
<int> &entry
)
141 return entry
!= nullptr;
145 #endif /* FOR_EACH */