Example : Simple.C

Classes/Techniques Demonstrated :

Simple.C is another simple program which demonstrates the basics of the HPCxx_Thread class. It creates several threads, each of which prints some information and does some inane time - killing calculting, then dies.

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



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;
    printf("constructor complete\n");
  }
  void run(){
    printf("hi from thread %d\n", my_num);
    double a = 1;
    for(int i = 0; i < 10000; i++)
      for(int j = 0; j < 1000; j++) a += sqrt((double) 1.0*j);
    printf("done with thinking in %d\n", my_num);
    c->incr();
    printf("done with write in %d\n", my_num);
  }
};

int foo(int n){
  HPCxx_CSem c(n);
  MyThread *t[100];
  for(int i = 0; i < n; i++){
    t[i] = new MyThread(&c, i);
    t[i]->start();
  }
  c.wait();
  return 0;
}

int main(int argc, char *argv[]){
  HPCxx_Group *g;
  hpcxx_init(argc, argv, g);
  int x;
  cout << "num threads:" ;
  cin >> x;
  cout << "doing " << x << "threads.";
  for(int i = 0; i < 10; i++){
    double a;
    cout << "*** iteration " << i << " ***" << endl;
    foo(x);
    for(int i = 0; i < 100000; i++)
      for(int j = 0; j < 1000; j++) a += sqrt((double) 1.0*j);
  }
  printf("done with read\n");
  hpcxx_exit(g);
  return(0);
} /* main() */

hpc++@extreme.indiana.edu

Last modified: Thu Apr 22 02:11:59 EST 1999