Repository navigation
Expand file tree
/
Copy pathTPINode.hpp
More file actions
113 lines (88 loc) · 2.55 KB
/
Copy pathTPINode.hpp
File metadata and controls
113 lines (88 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#ifndef TPINODE_HPP_
#define TPINODE_HPP_
#include <TPI.h>
#include <NoOpMemoryModel.hpp>
#include <iostream> // debug
inline
void tpi_work_span(TPI_Work* work, int n,
size_t& ibeg, size_t& iend)
{
const int chunk = ( n + work->count - 1 ) / work->count ;
iend = chunk * ( work->rank + 1 );
ibeg = chunk * ( work->rank );
if ( n < iend ) { iend = n; }
}
template<class WDP>
void tpi_execute(TPI_Work * work)
{
const WDP* const_wdp = static_cast<const WDP*>(work->info);
WDP* wdp = const_cast<WDP*>(const_wdp);
size_t n = wdp->n;
size_t ibeg = 0, iend = n;
tpi_work_span(work, n, ibeg, iend);
for(size_t i=ibeg; i<iend; ++i) {
(*wdp)(i);
}
}
template<class WDP>
void tpi_reduction_work(TPI_Work * work)
{
const WDP* wdp = static_cast<const WDP*>(work->info);
size_t n = wdp->n;
size_t ibeg = 0, iend = n;
tpi_work_span(work, n, ibeg, iend);
typedef typename WDP::ReductionType ReductionType;
ReductionType tmpres = wdp->result, tmpi;
for(size_t i=ibeg; i<iend; ++i) {
tmpi = wdp->generate(i);
tmpres = wdp->reduce(tmpres, tmpi);
}
*(static_cast<ReductionType*>(work->reduce)) = tmpres;
}
template<class WDP>
void tpi_reduction_join(TPI_Work * work, const void* src)
{
typedef typename WDP::ReductionType ReductionType;
const WDP* wdp = static_cast<const WDP*>(work->info);
ReductionType& work_reduce = *(static_cast<ReductionType*>(work->reduce));
work_reduce = wdp->reduce(work_reduce, *(static_cast<const ReductionType*>(src)) );
}
template<class WDP>
void tpi_reduction_init(TPI_Work * work)
{
typedef typename WDP::ReductionType ReductionType;
const WDP* wdp = static_cast<const WDP*>(work->info);
*(static_cast<ReductionType*>(work->reduce)) = wdp->identity();
}
class TPINode : public NoOpMemoryModel {
public:
TPINode(int numThreads=0)
: numThreads_(numThreads)
{
if (numThreads >= 1) {
TPI_Init(numThreads);
}
}
~TPINode()
{
if (numThreads_ >= 1) {
TPI_Finalize();
}
}
template <class WDP>
void parallel_for(int length, WDP & wd ) {
TPI_Run_threads(tpi_execute<WDP>, &wd, 0 );
}
template <class WDP>
void parallel_reduce(int length, WDP & wd ) {
typedef typename WDP::ReductionType ReductionType;
ReductionType result = 0;
TPI_Run_threads_reduce(tpi_reduction_work<WDP>, &wd,
tpi_reduction_join<WDP>,
tpi_reduction_init<WDP>, sizeof(result), &result);
wd.result = result;
}
private:
int numThreads_;
};
#endif