QMCPACK
ParallelExecutorSTD.hpp
Go to the documentation of this file.
1 ////////////////////////////////////////////////////////////////////////////////
2 // This file is distributed under the University of Illinois/NCSA Open Source
3 // License. See LICENSE file in top directory for details.
4 //
5 // Copyright (c) 2020 QMCPACK developers.
6 //
7 // File developed by: Peter Doak, doakpw@ornl.gov, Oak Ridge National Lab
8 // Ye Luo, yeluo@anl.gov, Argonne National Laboratory
9 //
10 // File created by: Peter Doak, doakpw@ornl.gov, Oak Ridge National Lab
11 ////////////////////////////////////////////////////////////////////////////////
12 
13 
14 /** @file
15  * @brief implementation of std::thread specialization of ParallelExecutor
16  */
17 #ifndef QMCPLUSPLUS_PARALLELEXECUTOR_STDTHREADS_HPP
18 #define QMCPLUSPLUS_PARALLELEXECUTOR_STDTHREADS_HPP
19 
20 #include <vector>
21 #include <functional>
22 #include <utility>
23 #include <thread>
24 
26 
27 namespace qmcplusplus
28 {
29 /** TaskWrapper code from
30  * https://stackoverflow.com/questions/48268322/wrap-stdthread-call-function
31  *
32  * Required to forward an arbitrary var args function
33  */
34 template<typename F>
36 {
37  F f;
38 
39  template<typename... T>
40  void operator()(T&&... args)
41  {
42  f(std::forward<T>(args)...);
43  }
44 };
45 
46 /** implements parallel tasks executed by STD threads. One task one thread mapping.
47  */
48 template<>
49 template<typename F, typename... Args>
50 void ParallelExecutor<Executor::STD_THREADS>::operator()(int num_tasks, F&& f, Args&&... args)
51 {
52  std::vector<std::thread> threads(num_tasks_);
53 
54  for (int task_id = 0; task_id < num_tasks; ++task_id)
55  {
56  threads[task_id] = std::thread(TaskWrapper<F>{std::forward<F>(f)}, task_id, std::forward<Args>(args)...);
57  }
58 
59  for (int task_id = 0; task_id < num_tasks; ++task_id)
60  {
61  threads[task_id].join();
62  }
63 }
64 
65 } // namespace qmcplusplus
66 
67 #endif
helper functions for EinsplineSetBuilder
Definition: Configuration.h:43
TaskWrapper code from https://stackoverflow.com/questions/48268322/wrap-stdthread-call-function.
void operator()(int num_tasks, F &&f, Args &&... args)
Concurrently execute an arbitrary function/kernel with task id and arbitrary args.