#include <iostream.h>
#include <hpcxx_rts.h>
#include <HPCxx_Sync.cc>
#include <hpcxx_invoke.cc>
#include <HPCxx_GlobalPtr.cc>
#include <hpcxx_invokeImpl.cc>
#include <HPCxx_GlobalRefImpl.cc>
class intAdd {
public:
int& operator()(int& x, int& y) { x += y; return x; }
};
class MyThread : public HPCxx_Thread {
HPCxx_Barrier& barrier;
HPCxx_Reduct1<int, intAdd> &add;
int* infoAr;
int totalThreads, myId, count, myReductKey;
public:
MyThread(int n, int id, HPCxx_Reduct1<int, intAdd>& r,
HPCxx_Barrier& _barrier) :
totalThreads(n), myId(id), add(r), barrier(_barrier), HPCxx_Thread()
{
add.synchronousSetUp();
myReductKey = add.getKey();
myBarrierKey = barrier.getKey();
}
void run() {
int myTotal = 0, total = 0;
infoAr = new int[10];
srand48((int)infoAr);
cout << "Thread " << myId << " generating array values..." << endl;
for(count = 0; count < 10; count++) {
infoAr[count] = (int)(1000 * drand48());
myTotal += infoAr[count];
}
cout << "Thread " << myId << " finished and calling reduction..." << endl;
total = add(myReductKey, myTotal);
cout << "Thread " << myId << " received sum " << total << endl << flush;
cout << "Thread " << myId << " now calling reduction on my array"
<< endl << flush;
// The arguments are : key, array, number of array elements
total = add(myReductKey, infoAr, 10);
cout << "Thread " << myId << " received second sum " << total
<< endl << flush;
barrier(myBarrierKey);
}
};
int run_threads(int n, HPCxx_Reduct1<int, intAdd> add, HPCxx_Barrier& barrier)
{
MyThread* t[n];
int total, count, myTotal = 0;
int* infoAr = new int[10];
for(count = 0; count < 10; count++) {
infoAr[count] = (int)(1000 * drand48());
myTotal += infoAr[count];
}
int key0, key1;
key0 = barrier.getKey();
for(int i = 0; i < n; i++) {
t[i] = new MyThread(n, i, add, barrier);
t[i]->start();
}
add.synchronousSetUp();
key1 = add.acquireKey();
total = add(key1, myTotal);
cout << "Main process received sum " << total << endl << flush;
total = add(key1, infoAr, 10);
cout << "Main process received second sum " << total << endl << flush;
barrier(key0);
for(int i = 0; i < n; i++)
t[i]->join();
return 0;
}
int main(int argc, char** argv)
{
HPCxx_Group* g;
hpcxx_init(argc, argv, g);
int num_threads;
cout << "enter number of threads : ";
cin >> num_threads;
cout << "using " << num_threads << " threads." << endl << flush;
g->setNumThreads(num_threads + 1);
HPCxx_Barrier barrier(*g);
HPCxx_Reduct1<int, intAdd> r(g, intAdd());
run_threads(num_threads, r, barrier);
cout << "DONE" << endl << flush;
hpcxx_exit(g);
return 0;
}
|