#include <iostream.h>
#include <hpcxx_rts.h>
class MyThread : public HPCxx_Thread {
HPCxx_Barrier& barrier;
int* infoAr;
int totalThreads, myId, count, myKey;
public:
MyThread(int n, int id, int* ar, HPCxx_Barrier& _barrier):
totalThreads(n), myId(id), infoAr(ar), barrier(_barrier),
HPCxx_Thread() { }
void run()
{
int total = 0;
myKey = barrier.getKey();
cout << "Thread " << myId << " generating array values..." << endl;
for(count = 10 * myId; count < 10 * (myId + 1); count++) {
infoAr[count] = (int)(1000 * drand48());
}
cout << "Thread " << myId << " finished and entering barrier..." << endl;
// wait here until all threads are finished with array generation
barrier(myKey);
// sum shared array to show that all threads have same array in same state
for(count = 0; count < 10 * totalThreads; count++) {
total += infoAr[count];
}
cout << "Thread " << myId << " computed sum : " << total << endl;
}
};
int run_threads(int n, HPCxx_Barrier barrier)
{
MyThread* t[n];
int* infoAr = new int[n * 10];
int count = 0, key0;
// give the main process a key to the barrier
key0 = barrier.getKey();
for(int i = 0; i < n; i++) {
t[i] = new MyThread(n, i, infoAr, barrier);
t[i]->start();
}
// wait here until all of the threads are finished
barrier(key0);
for(int k = 0; k < n; k++)
t[k]->join();
for(count = 0; count < n * 10; count++) {
cout << "Array value " << count << " is " << infoAr[count]
<< endl << flush;
}
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);
run_threads(num_threads, barrier);
cout << "DONE" << endl << flush;
hpcxx_exit(g);
return 0;
}
|