Example : SyncQ.C

Classes/Techniques Demonstrated :

SyncQ.C demonstrates the basics of the HPCxx_SyncQ class. It creates several threads and hands them each a pointer to the same SyncQ variable. Each thread sleeps for a few seconds, writes a value to the SyncQ and then quits. Meanwhile, the main function is in a loop attempting to read the SyncQ variable. Each time a thread writes to the variable, the function is released to deliver the value received to the user. It then continues looping until it has received a value from each thread.

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

class MyThread: public HPCxx_Thread{
  HPCxx_SyncQ<int>* sync;
  int my_num;

public:
  MyThread( HPCxx_SyncQ<int>* s , int m ):  HPCxx_Thread(){
    my_num = m;
    sync = s;
    cout << "Thread " << my_num << " constructor complete" << endl 
         << flush;
  }
  void run(){
    cout << "Thread " << my_num << " sleeping..." << endl << flush;
    sleep((10-my_num));
    *sync=my_num;
    cout << "Thread " << my_num << " inserted value : " 
	 << my_num << endl << flush;
  }
};


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;

  HPCxx_SyncQ<int> s;
  MyThread* t[num_threads];
  int temp;
  

  //
  // Create and begin execution of threads
  //
  for(int i = 0; i < num_threads; i++){
    t[i] = new MyThread(&s, i);
    t[i]->start();
  }

  for(i = 0; i < num_threads; i++) {
    // block here waiting for a thread to write to queue s
    temp = s;
    cout << "Received value " << temp << endl << flush;
  }

  //
  // Wait for threads to finish
  //
  for(int i = 0; i < num_threads; i++)
    t[i]->join();

  cout << "DONE\n";
  hpcxx_exit(g);
  return(0);
}

Benjamin Temko
Last modified: Thu Jun 25 11:09:16 EST 1998