//CSE 660
//Jason Kim
//Lab 3

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
#include <signal.h>
#include <wait.h>
#include "sshm.h"
#include "ssem.h"

using namespace std;


//code of Proc3

int main()
{
	int i, internal_reg;
	int semid1,semid2,semid3;
	
	//get semid
	semid1 = sem_open(1);
	semid2 = sem_open(2);
	semid3 = sem_open(3);

	/* synchronize with proc1 and Proc3 (3 process 3 way synchronization)*/
	sem_signal(semid1);
	sem_signal(semid2);
	sem_wait(semid3);
	sem_wait(semid3);
	
	//open shared memory
	int shid; // for remove
	int *Account;
	shid = shm_get(123,(void**)&Account,3*sizeof(int));

      for (i = 0; i < 1000; i++)
      {
          internal_reg = Account[2];                /*Proc3 takes from Account[2]*/   
          internal_reg = internal_reg - 100;
          Account[1] = internal_reg;

   	    /* same thing, except we're adding $100 to Account2 now... */
          internal_reg = Account [0];      /*Proc3 adds into Account[0]*/
          internal_reg = internal_reg + 100;
          Account[0] = internal_reg;
   	    /*     Here add a code that prints contents of each account
          after 100th, 200th, 300th, ...., and 1000th iterations*/ 
	    if (i%100==0)
	    {
		cout << Account[0] << endl;
		cout << Account[1] << endl;
		cout << Account[2] << endl;
	    }	
      }
	/*proc3 to remove all shared memories and semaphores*/

	//remove shared memories
	shm_rm(shid);


	//remove semaphores
	sem_rm(semid1);
	sem_rm(semid2);
	sem_rm(semid3);
	

	return 0;
}
/*in the code above include some wait and signal operations on semaphores. Do not over-synchronize. */


