/* L-27 MCS 572 Friday 17 March 2006 : shared bank acocunt.
 * Compile this example on copper as "cc_r -o bank bank.c"
 * and run it typing "bank" at the prompt. */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *withdraw ( void *n );
/* 
 * DESCRIPTION :
 *   On entry is the number of the executing thread.
 *   Lists the current balance and prompts the user for a withdrawal,
 *   on return is the current value of the balance. */

int main ( int argc, char *argv[] )
{
   int *n = (int*)calloc(1,sizeof(int));
   int p = 2;
   int r[p],i;
   pthread_t t[p];
   
   for(i=0; i<p; i++)
      pthread_create(&t[i],NULL,withdraw,(void*)&i);
 
   for(i=0; i<p; i++)
   {
      pthread_join(t[i],(void **)&n);
      r[i] = *n;
   }

   for(i=0; i<p; i++)
      printf("After withdrawal by thread %d, the balance is %d.\n",i,r[i]);

   return 0;
}

void *withdraw ( void *n )
{
   static int balance = 983;
   int *nb = (int*)n;
   int amount;
   int *d = (int*)calloc(1,sizeof(int));

   static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

   pthread_mutex_lock(&lock);   /* enter the critical section */

   printf("Hi thread %d, the balance is %d, give amount to withdraw : ",
           *nb,balance);
   scanf("%d",&amount);

   balance = balance - amount;

   pthread_mutex_unlock(&lock); /* leave the critical section */

   *d = balance;

   return (void*)d;
}
