; (Critical Section) In a bank there are two accounts A and B. The following thr
ID: 672230 • Letter: #
Question
;
(Critical Section) In a bank there are two accounts A and B. The following three transactions occur at nearly the same time: transfer of $500 from A to B, withdrawal of $1000 from A, and withdrawal of $1000 from B.
If the three transactions execute sequentially, one can withdraw $1000 from either account A or account B, but not both at the same time. For example, the sequence ‘transfer, then withdrawA, then withdrawB’ results in the execution order ‘t1, t2, t4, t5, a1, a2, a3, a6, b1, b2, b4, b5, b6’. However, when they are executed concurrently, the bank may accept both withdrawals. Give an execution order that allows withdrawal of $1000 from both accounts.
Identify the critical sections and use one (or two) semaphore to protect the critical sections in the above code. Remember to initialize the semaphores
Explanation / Answer
the bank may accept both withdrawals in this execution order: t1 t2 a1 a2 t4 t5 a4 a5 a6 b1 b2 b4 b5 b6
#include<sempaphore.h>
#include<stdlib.h>
sem_t n;
sem_init(&n, 0, 1);
void transfer(){
in x=500;
sem_wait(&n);
if(accountA<x)
//body continue
sem_post(&n);
}
void withdrawA(){
int x=1000;
sem_wait(&n);
if(accountA<x)
//body continue
sem_signal(&n);
}
int main(int argc, char *argv[]) {
pthread_t t,wA,wB;
Pthread_create(&t, NULL,transfer, NULL);
Pthread_create(&wA, NULL,withdrawA, NULL);
Pthread_create(&wB, NULL,withdrawB, NULL);
Pthread_join(t, NULL);
Pthread_join(wA, NULL);
Pthread_join(wB, NULL);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.