Example : Simple.C

Classes/Techniques Demonstrated :

Simple.C is another simple program which demonstrates the basics of the HPCxx_Thread class. In each iteration of a loop, it creates a user-defined number of threads, each of which prints some information, does some inane time-killing calculation, and then dies.

This program also adds semaphores into the mix. Each thread is given a pointer to a semaphore c, which it increments at the end of its life cycle. Not until every thread has incremented the semaphore will the function run_threads return. This demonstrates one way of implementing synchronization.

#include <hpcxx_rts.h>
#include <iostream.h>
#include <math.h>

class MyThread: public HPCxx_Thread{
  HPCxx_CSem* c;
  int my_num;

public:
  MyThread(HPCxx_CSem* s , int m): HPCxx_Thread() {
    my_num = m;
    c = s;
    cout << "Thread " << my_num << " constructor complete" << endl;
  }
  
  void run() {
    cout << "Hi from thread " << my_num << endl;

    // start inane calculation
    double a = 1.0;
    for(int j = 0; j < 1000; j++) a += sqrt(1.0 * j);
    cout << "done with thinking in " << my_num << endl;

    // increment the semaphore before quitting
    c->incr();
    cout << "done with write to semaphore in " << my_num << endl;
  }
};

int start_threads(int n){
  HPCxx_CSem c(n);
  MyThread* t[n];

  // create n threads and start them running
  for(int i = 0; i < n; i++){
    t[i] = new MyThread(&c, i);
    t[i]->start();
  }

  // block here until all n threads have incremented semaphore
  c.wait();
  for(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.\n";
  
  for(int i = 0; i < num_threads; i++) {
    double a = 1.0;
    cout << "*** iteration " << i << " ***" << endl;
    start_threads(num_threads);
    for(int j = 0; j < 1000; j++) a += sqrt(1.0 * j);
  }
  
  cout << "DONE" << endl;
  hpcxx_exit(g);
  return(0);
}

Benjamin Temko
Last modified: Tue Jul 7 9:46:09 MDT 1998