1 /* parmap_test -- test parmap */
3 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
8 #include "src/internal_config.h" // HAVE_FUTEX_H
9 #include "src/xbt/parmap.hpp"
10 #include <simgrid/s4u/Engine.hpp>
16 #include <numeric> // std::iota
20 XBT_LOG_NEW_DEFAULT_CATEGORY(parmap_test, "Test for parmap");
22 static int test_parmap_basic(e_xbt_parmap_mode_t mode)
25 for (unsigned num_workers = 1; num_workers <= 16; num_workers *= 2) {
26 const unsigned len = 1033;
27 const unsigned num = 5;
29 simgrid::xbt::Parmap<unsigned*> parmap(num_workers, mode);
30 std::vector<unsigned> a(len);
31 std::vector<unsigned*> data(len);
32 std::iota(begin(a), end(a), 0);
33 std::iota(begin(data), end(data), &a[0]);
35 for (unsigned i = 0; i < num; i++)
36 parmap.apply([](unsigned* arg) { *arg = 2 * *arg + 1; }, data);
38 for (unsigned i = 0; i < len; i++) {
39 unsigned expected = (1U << num) * (i + 1) - 1;
40 if (a[i] != expected) {
41 XBT_CRITICAL("with %u threads, a[%u]: expected %u, got %u", num_workers, i, expected, a[i]);
50 static int test_parmap_extended(e_xbt_parmap_mode_t mode)
54 for (unsigned num_workers = 1; num_workers <= 16; num_workers *= 2) {
55 const unsigned len = 2 * num_workers;
57 simgrid::xbt::Parmap<std::thread::id*> parmap(num_workers, mode);
58 std::vector<std::thread::id> a(len);
59 std::vector<std::thread::id*> data(len);
60 std::iota(begin(data), end(data), &a[0]);
62 unsigned sleep_ms = 10;
66 [sleep_ms](std::thread::id* arg) {
67 *arg = std::this_thread::get_id();
68 std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
71 std::sort(begin(a), end(a));
72 count = static_cast<unsigned>(std::distance(begin(a), std::unique(begin(a), end(a))));
73 if (count == num_workers || sleep_ms > 250)
76 XBT_DEBUG("Failure. Try again with duration = %ums", sleep_ms);
78 if (count != num_workers) {
79 XBT_CRITICAL("only %u/%u threads did some work", count, num_workers);
86 int main(int argc, char** argv)
89 xbt_log_control_set("parmap_test.fmt:[%c/%p]%e%m%n");
90 simgrid::s4u::Engine e(&argc, argv);
91 simgrid::kernel::context::Context::set_nthreads(16); // dummy value > 1
93 XBT_INFO("Basic testing posix");
94 status += test_parmap_basic(XBT_PARMAP_POSIX);
95 XBT_INFO("Basic testing futex");
97 status += test_parmap_basic(XBT_PARMAP_FUTEX);
99 XBT_INFO("Basic testing busy wait");
100 status += test_parmap_basic(XBT_PARMAP_BUSY_WAIT);
102 XBT_INFO("Extended testing posix");
103 status += test_parmap_extended(XBT_PARMAP_POSIX);
104 XBT_INFO("Extended testing futex");
106 status += test_parmap_extended(XBT_PARMAP_FUTEX);
108 XBT_INFO("Extended testing busy wait");
109 status += test_parmap_extended(XBT_PARMAP_BUSY_WAIT);
111 return status == 0 ? EXIT_SUCCESS : EXIT_FAILURE;