1.. _Advanced_Example:
2
3Advanced Example
4================
5
6
7An example of a more advanced associative operation is to find the index
8where ``Foo(i)`` is minimized. A serial version might look like this:
9
10
11::
12
13
14   long SerialMinIndexFoo( const float a[], size_t n ) {
15       float value_of_min = FLT_MAX;        // FLT_MAX from <climits>
16       long index_of_min = -1;
17       for( size_t i=0; i<n; ++i ) {
18           float value = Foo(a[i]);
19           if( value<value_of_min ) {
20               value_of_min = value;
21               index_of_min = i;
22           }
23       }
24       return index_of_min;
25   }
26
27
28The loop works by keeping track of the minimum value found so far, and
29the index of this value. This is the only information carried between
30loop iterations. To convert the loop to use ``parallel_reduce``, the
31function object must keep track of the carried information, and how to
32merge this information when iterations are spread across multiple
33threads. Also, the function object must record a pointer to ``a`` to
34provide context.
35
36
37The following code shows the complete function object.
38
39
40::
41
42
43   class MinIndexFoo {
44       const float *const my_a;
45   public:
46       float value_of_min;
47       long index_of_min;
48       void operator()( const blocked_range<size_t>& r ) {
49           const float *a = my_a;
50           for( size_t i=r.begin(); i!=r.end(); ++i ) {
51              float value = Foo(a[i]);
52              if( value<value_of_min ) {
53                  value_of_min = value;
54                  index_of_min = i;
55              }
56           }
57       }
58    
59
60       MinIndexFoo( MinIndexFoo& x, split ) :
61           my_a(x.my_a),
62           value_of_min(FLT_MAX),    // FLT_MAX from <climits>
63           index_of_min(-1)
64      {}
65    
66
67       void join( const SumFoo& y ) {
68           if( y.value_of_min<value_of_min ) {
69               value_of_min = y.value_of_min;
70               index_of_min = y.index_of_min;
71           }
72       }
73
74
75       MinIndexFoo( const float a[] ) :
76           my_a(a),
77           value_of_min(FLT_MAX),    // FLT_MAX from <climits>
78           index_of_min(-1),
79       {}
80   };
81
82
83Now ``SerialMinIndex`` can be rewritten using ``parallel_reduce`` as
84shown below:
85
86
87::
88
89
90   long ParallelMinIndexFoo( float a[], size_t n ) {
91       MinIndexFoo mif(a);
92       parallel_reduce(blocked_range<size_t>(0,n), mif );
93
94
95    return mif.index_of_min;
96   }
97