#include <unistd.h>
#include <cstdio>
#include <iostream>
#include <pthread.h>

//include "ShmObject.hh"
#include "SemOpen.hh"
#include "SemClosed.hh"

// MUST INCLUDE RIGHT LIB USING g++ test.cc -lpthread

using namespace std;

SemOpen *s;
unsigned *p;

void* threadRoutine1(void *) {
  //  ShmObject<SemOpen> shmSem(5678);
  //    SemOpen *s(shmSem.payload());

  //       while(true) {
  for(unsigned i(0);i<10;i++) {
    cout << "C Incrementing with value = " << s->value() << endl;
        (*s)++;
    (*p)++;
    cout << "C Sleeping with value = " << s->value() 
	 << " n = " << *p << endl;
    sleep(2);
  }
  return 0;
}

void* threadRoutine2(void *) {
  //  ShmObject<SemOpen> shmSem(5678);
  //  SemOpen *s(shmSem.payload());

  //  while(true) {
  for(unsigned j(0);j<10;j++) {
    cout << "P Decrementing with value = " << s->value() << endl;
    (*s)--;
    cout << "P Sleeping with value = " << s->value()
	 << " n = " << *p  << endl;
    //sleep(1);
  }
    
  return 0;
}

int main() {
//  ShmObject<unsigned> shmU(5679);
//  unsigned *p(shmU.payload());

  //  unsigned n;
  //  unsigned *p(&n);

  SemOpen sobj;
  cout << "Initial value = " << sobj.value() << endl;
  s=&sobj;

  unsigned n;
  p=&n;
  *p=789;

  pthread_t pt;
  pthread_create(&pt,0,threadRoutine1,0);

  threadRoutine2(0);
};
