Mantid
Loading...
Searching...
No Matches
ParallelRunner.h
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2017 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7#pragma once
8
9#include "MantidParallel/Communicator.h"
10#include "MantidParallel/DllConfig.h"
11
12#include <memory>
13
14#include <functional>
15#include <thread>
16
17namespace ParallelTestHelpers {
18
25public:
27 ParallelRunner(const int threads);
28
29 int size() const;
30
31 template <class Function, class... Args> void runSerial(Function &&f, Args &&...args);
32 template <class Function, class... Args> void runParallel(Function &&f, Args &&...args);
33
34private:
35 std::shared_ptr<Mantid::Parallel::detail::ThreadingBackend> m_backend;
36 std::shared_ptr<Mantid::Parallel::detail::ThreadingBackend> m_serialBackend;
37};
38
39template <class Function, class... Args> void ParallelRunner::runSerial(Function &&f, Args &&...args) {
40 f(Mantid::Parallel::Communicator(m_serialBackend, 0), std::forward<Args>(args)...);
41}
42
43template <class Function, class... Args> void ParallelRunner::runParallel(Function &&f, Args &&...args) {
44 if (!m_backend) {
45 Mantid::Parallel::Communicator comm;
46 f(comm, std::forward<Args>(args)...);
47 } else {
48 std::vector<std::thread> threads;
49 for (int t = 0; t < m_backend->size(); ++t) {
50 Mantid::Parallel::Communicator comm(m_backend, t);
51 threads.emplace_back(std::forward<Function>(f), comm, std::forward<Args>(args)...);
52 }
53 for (auto &t : threads) {
54 t.join();
55 }
56 }
57}
58
59template <class... Args> void runParallel(Args &&...args) {
60 ParallelRunner runner;
61 runner.runParallel(std::forward<Args>(args)...);
62}
63
64} // namespace ParallelTestHelpers
Runs a callable in parallel.
void runSerial(Function &&f, Args &&...args)
std::shared_ptr< Mantid::Parallel::detail::ThreadingBackend > m_backend
void runParallel(Function &&f, Args &&...args)
std::shared_ptr< Mantid::Parallel::detail::ThreadingBackend > m_serialBackend
void runParallel(Args &&...args)