4. Write a C program to simulate deposit/withdraw activities on a banking accoun
ID: 3832848 • Letter: 4
Question
4. Write a C program to simulate deposit/withdraw activities on a banking account. (Hint: you might want to review Lab 3 slides.) (25 points)
Declare the balance as a global variable and initialize it to 600.
Write two functions, one for withdraw, the other for deposit. Both withdraw and deposit functions have one parameter, which represent the amount to withdraw or deposit. The functions deduct the balance and add to the balance one dollar at a time, respectively. Therefore, to withdraw 600 thousands, for example, the withdraw function has to execute a loop with 600 thousand iterations. The deposit function works in the same way, in the reverse direction.
Create two Posix threads in main(), which call the withdraw and the deposit function respectively.
Use pthread_mutex_lock() and pthread_mutex_unlock() functions to ensure mutual exclusion between the two threads. Also make sure to use pthread_join() to wait for the threads to terminate.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int balance;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *withdraw(void *vargp){
printf("The balance available is : %d ",balance);
int Damount=600000;
printf("The amount to be deducted is : %d ", Damount);
int i;
pthread_mutex_lock(&mutex);
for(i=0;i<=Damount;i++){
balance=balance--;
printf("The value of balance is : %d ", balance);
}
printf("The balance after withdraw is : %d ",balance);
pthread_mutex_unlock(&mutex);
}
void *deposit(void *vargp){
int init_amount=balance;
printf("The initial value saved is : %d ", balance);
pthread_mutex_lock(&mutex);
int amount=600000;
printf("The Deposit value is : %d ", amount);
int MaxDep = amount+init_amount;
printf("The Deposited sum value will be : %d ", MaxDep);
for(balance;balance<MaxDep;balance++){
;
}
pthread_mutex_unlock(&mutex);
}
int main()
{
balance=600;
// Depositing Thread :
pthread_t tid1;
printf("Before Thread ");
pthread_mutex_lock(&mutex);
pthread_create(&tid1, NULL, deposit, NULL);
pthread_mutex_unlock(&mutex);
pthread_join(tid1, NULL);
printf("After Thread ");
printf("The balance is : %d ", balance );
//Withdraw Thread :
pthread_t tid2;
printf("Before Thread ");
pthread_mutex_lock(&mutex);
pthread_create(&tid2, NULL, withdraw, NULL);
pthread_mutex_unlock(&mutex);
pthread_join(tid2, NULL);
printf("After Thread ");
printf("The balance is : %d ", balance );
exit(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.