Example : Mutex.C

Classes/Techniques Demonstrated :

Mutex.C

Mutex.c demonstrates a trivial example of delineating a section of code as a critical section through the use of the HPCxx_Mutex object. Unlike Java, the library cannot support synchronized methods or CC++ atomic members, but the simple Mutex object with two functions, lock and unlock provide the basic capability.
class MyThread : public HPCxx_Thread {
  HPCxx_CSem *sem;
  HPCxx_Mutex l;
  int &sharedVal;
  int myId;
  
public:
  MyThread(int id, HPCxx_CSem *_sem, int &sv ):
    myId(id), sem(_sem), sharedVal(sv), HPCxx_Thread(){}
  void run() {

    sleep((unsigned)3);
    cout << "Thread " << myId << " waiting for my turn..." << endl;

    l.lock(); // critical section
    cout << "Thread " << myId << " has critical section!" << endl;
    sharedVal+=myId;
    l.unlock();

    sem->incr();
    cout << "Thread " << myId << " added in my value (exiting)." << endl;
  } 
};

int foo(int n){
  HPCxx_CSem c(n);
  MyThread *t[100];
  int total=0;
  
  for(int i = 0; i < n; i++){
    t[i] = new MyThread(i, &c, total);
    t[i]->start();
  }
  c.wait();
  cout << " Total of thread IDs is : " << total << endl << flush;
  cout << "DONE" << endl << flush;
  return 0;
}


int main(int argc, char **argv)
{
  HPCxx_Group *g;
  hpcxx_init(argc, argv, g);
  int n;
  
  cout << "Number of threads : " << endl << flush;
  cin >> n;
  foo(n);
  return hpcxx_exit(g);
}

hpc++@extreme.indiana.edu

Last modified: Thu Apr 22 02:12:27 EST 1999