Stride Reference Manual  1.0
openmp.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <vector>
4 #include "unipar.h"
5 #include "interface.h"
6 #include <omp.h>
7 
8 namespace unipar {
9 namespace internal {
10 
11 template<typename Impl, typename... Types>
13 
14 template<typename Impl, typename Type, typename... Rest>
15 class OpenmpResourceManager<Impl, Type, Rest...> : public ResourceManager<Impl, Type, Rest...> {
16 public:
17  using RestType = typename Impl::template RMType<Impl, Rest...>;
18  using FuncType = std::function<Type()>;
19 
20  // Copy constructor does NOT copy the values!
21  using ResourceManager<Impl, Type, Rest...>::ResourceManager;
22 
23  template<typename F, typename... Args>
24  typename std::result_of<F(Type&, Args...)>::type call(const F& to_call, Args&& ... args) {
25  auto& value = m_values[omp_get_thread_num()];
26  if (value == nullptr) {
27  value = new Type(std::move(this->m_func()));
28  }
29  return this->m_rest.call(to_call, *value, std::forward<Args>(args)...);
30  }
31 
32  void init(size_t size) {
33  m_values.resize(size, nullptr);
34  this->m_rest.init(size);
35  }
36 
38  for (auto& v: m_values) {
39  if (v) {
40  delete v;
41  v = nullptr;
42  }
43  }
44  }
45 
46 protected:
47  std::vector<Type*> m_values;
48 };
49 
50 template<typename Impl>
51 class OpenmpResourceManager<Impl> : public ResourceManager<Impl> {
52 public:
53  void init(size_t) {}
54 };
55 
57 public:
58  template<typename Impl, typename... Types>
59  using RMType = OpenmpResourceManager<Impl, Types...>;
60 
62  #pragma omp parallel
63  {
64  m_nthreads = omp_get_num_threads();
65  }
66  }
67 
68  _OpenmpParallel(int nthreads) : m_nthreads(nthreads) {}
69 
70  template<typename RM>
71  void init(RM& rm) {
72  rm.init(m_nthreads);
73  }
74 
75  template<typename IndexF, typename IndexL, typename IndexS, typename Func, typename RM>
76  void parallelFor(IndexF first, IndexL last, IndexS step, const Func& f, RM& rm) {
77  #pragma omp parallel for num_threads(m_nthreads) schedule(runtime)
78  for (IndexF i = first; i < last; i += step) {
79  rm.call(f, i);
80  }
81  }
82 
83  inline int getNumThreads() const { return m_nthreads; }
84 
85  inline void setNumThreads(int nthreads) { m_nthreads = nthreads; }
86 
87 private:
89 };
90 
91 }
92 
94 
95 }
void parallelFor(IndexF first, IndexL last, IndexS step, const Func &f, RM &rm)
Definition: openmp.h:76
typename Impl::template RMType< Impl, Rest... > RestType
Definition: openmp.h:17
void setNumThreads(int nthreads)
Definition: openmp.h:85
_OpenmpParallel(int nthreads)
Definition: openmp.h:68
Unified Parallelisation.
Definition: dummy.h:7
std::result_of< F(Type &, Args...)>::type call(const F &to_call, Args &&...args)
Definition: openmp.h:24