Previous: Hello World Up: Examples Next: Multiple-Reader Multiple-Writer Linked List
This program finds the minimum element of a statically defined integer array.
#include <iostream.h> const int N = 8; int A[N] = {3, 4, 5, 1, 2, 5, 9, 6};class Min { private: int current_min;
public: Min(int i) { current_min = i; cout << "minimum initialized at " << current_min << endl; }
atomic void check (int i) { cout << "comparing " << i << "..."; if (i<current_min) current_min = i; cout << "minimum so far is " << current_min << endl; }
int value (void) { return current_min; } };
int main() { Min m(A[0]); parfor (int i=1; i<N; i++) m.check(A[i]);
return m.value(); }
Each element of the array is compared to the smallest value seen so far. If the element is smaller, then the smallest value seen so far is updated. By the nature of a parfor loop, we do not know the order in which elements will be compared using class m. The atomicity of the member check(), however, guarantees that there will be no interference between concurrent threads operating on m. Thus, the mutable variable m.current_min is protected, and the result of the program is deterministically the smallest element of the array.