Example : Sync.C

Classes/Techniques Demonstrated :

Sync.C demonstrates the basics of the HPCxx_Sync class. It creates several threads, assigning each its own Sync variable. Each thread blocks on its Sync variable, waiting to be released. The user inputs a number indicating which thread to release. The program writes to that thread's Sync variable, thus releasing the thread. When all threads have been released, the program ends.

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

const int NUMWORKERS 3;

class Worker: public HPCxx_Thread {
  HPCxx_Sync<int>& s;
  int myID;

public:
  Worker(HPCxx_Sync<int>& s_, int i): s(s_), myID(i), HPCxx_Thread()
  {
    cout << "Thread " << myID << " constructor complete" << endl;
  }
  void run() 
  {
    int x;

    // Block here until s is set to something in main program       
    x = s;
    cout << "Thread " << myID << " thanks you for your support " << endl
         << flush;
  }
};


int main(int argc, char **argv)
{
  int tr = -1, nw = NUMWORKERS, released[NUMWORKERS];
  HPCxx_Group* g;
  HPCxx_Sync<int> t_sync[NUMWORKERS];

  hpcxx_init(argc, argv, g);

  cout << "Number of threads is " << NUMWORKERS << endl;

  // Create the threads and start them running
    Worker** w = new Worker*[NUMWORKERS];

  for(int i = 0; i < NUMWORKERS; i++) {
    w[i] = new Worker(t_sync[i], i);
    w[i]->start();
    released[i] = 0;
  }

  // loop until all threads are released
  while(nw) {

    // loop until user chooses a valid (unreleased) thread to release
    while(tr == -1 || released[tr]) {
      cout << endl << endl << "Thread to release ->";
      cin >> tr;
      if (released[tr])
	cout << "Sorry, thread " << tr << " was already released. "
	     << "Try again." << endl;
    }
   
    // release thread by setting thread's sync variable (t_sync[tr]) 
    //    to tr
    t_sync[tr] = tr;
    released[tr] = 1;
    tr = -1;
    nw--;
  }

  //
  // Wait for threads to finish
  //
  for(int i = 0; i < NUMWORKERS; i++)
    w[i]->start();

  cout << "All threads released." << endl;
  cout << "DONE" << endl;
  hpcxx_exit(g);
  return 0;
}

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