|
| 1 | +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. |
| 2 | +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. |
| 3 | +// All rights not expressly granted are reserved. |
| 4 | +// |
| 5 | +// This software is distributed under the terms of the GNU General Public |
| 6 | +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". |
| 7 | +// |
| 8 | +// In applying this license CERN does not waive the privileges and immunities |
| 9 | +// granted to it by virtue of its status as an Intergovernmental Organization |
| 10 | +// or submit itself to any jurisdiction. |
| 11 | + |
| 12 | +/// \file testSimRandom.cxx |
| 13 | +/// \author Sandro Wenzel (CERN) |
| 14 | +/// \brief Checks that o2::base::simRandom() defaults to gRandom and is per thread |
| 15 | + |
| 16 | +#define BOOST_TEST_MODULE Test SimRandom |
| 17 | +#define BOOST_TEST_MAIN |
| 18 | +#define BOOST_TEST_DYN_LINK |
| 19 | +#include <boost/test/unit_test.hpp> |
| 20 | + |
| 21 | +#include "DetectorsBase/SimRandom.h" |
| 22 | +#include <TRandom.h> |
| 23 | +#include <TRandom3.h> |
| 24 | +#include <thread> |
| 25 | +#include <vector> |
| 26 | + |
| 27 | +BOOST_AUTO_TEST_CASE(defaults_to_gRandom) |
| 28 | +{ |
| 29 | + BOOST_CHECK(o2::base::simRandom() == gRandom); |
| 30 | + TRandom3 own(1); |
| 31 | + o2::base::setSimRandom(&own); |
| 32 | + BOOST_CHECK(o2::base::simRandom() == &own); |
| 33 | + o2::base::setSimRandom(nullptr); |
| 34 | + BOOST_CHECK(o2::base::simRandom() == gRandom); |
| 35 | +} |
| 36 | + |
| 37 | +BOOST_AUTO_TEST_CASE(per_thread_generators) |
| 38 | +{ |
| 39 | + // each thread draws from its own generator; equal seeds give equal sequences, whatever the other threads do |
| 40 | + constexpr int nthreads = 8; |
| 41 | + constexpr int ndraws = 1000; |
| 42 | + std::vector<std::vector<double>> draws(nthreads); |
| 43 | + std::vector<std::thread> threads; |
| 44 | + for (int t = 0; t < nthreads; ++t) { |
| 45 | + threads.emplace_back([t, &draws]() { |
| 46 | + TRandom3 own(t % 2 + 1); |
| 47 | + o2::base::setSimRandom(&own); |
| 48 | + for (int i = 0; i < ndraws; ++i) { |
| 49 | + draws[t].push_back(o2::base::simRandom()->Rndm()); |
| 50 | + } |
| 51 | + o2::base::setSimRandom(nullptr); |
| 52 | + }); |
| 53 | + } |
| 54 | + for (auto& th : threads) { |
| 55 | + th.join(); |
| 56 | + } |
| 57 | + for (int t = 2; t < nthreads; ++t) { |
| 58 | + BOOST_CHECK(draws[t] == draws[t % 2]); |
| 59 | + } |
| 60 | + BOOST_CHECK(draws[0] != draws[1]); |
| 61 | + // the main thread was never changed |
| 62 | + BOOST_CHECK(o2::base::simRandom() == gRandom); |
| 63 | +} |
0 commit comments