Question: //C programming. #include #include #include #include //global variable defined struct { int balance[2]; } Bank={ {100,100} }; //routine for thread execution void* MakeTransactions() { int
//C programming.
#include
#include
#include
#include
//global variable defined
struct {
int balance[2];
}
Bank={
{100,100}
};
//routine for thread execution
void* MakeTransactions() {
int i, j, tmp1, tmp2, rint;
double dummy;
for (i=0; i < 3; i++) {
rint = (rand()%30)-15;
if (((tmp1=Bank.balance[0])+rint)>=0 && ((tmp2=Bank.balance[1])-rint)>=0) {
Bank.balance[0] = tmp1 + rint;
// spend time on purpose
for (j=0; j < rint*1000; j++) {
dummy=2.345*8.765/1.234;
}
Bank.balance[1] = tmp2 - rint;
}
}
return NULL;
}
int main(int argc, char **argv) {
int i;
void* voidptr=NULL;
pthread_t tid[2];
srand(getpid());
printf("Init balances A:%d + B:%d ==> %d! ",
Bank.balance[0], Bank.balance[1],
Bank.balance[0]+Bank.balance[1]);
for (i=0; i<2; i++) if (pthread_create(&tid[i],
NULL,MakeTransactions, NULL)) {
perror("Error in thread creating ");
return(1);
}
for (i=0; i<2; i++) if (pthread_join(tid[i],
(void*)&voidptr)) {
perror("Error in thread joining ");
return(1);
}
printf("Let's check the balances A:%d + B:%d ==> %d ?= 200 ",
Bank.balance[0],Bank.balance[1],
Bank.balance[0]+Bank.balance[1]);
return 0;
}
1. Use thread library calls (mutex lock and unlock) to modify the code in Q1) to remove any potential race conditions. Show your modification of the code and explain the outcome with your modification
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
