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 < 100; i++) {

rint = (rand()%30)-15;

if (((tmp1=Bank.balance[0])+rint)>=0 &&

((tmp2=Bank.balance[1])-rint)>=0) {

Bank.balance[0] = tmp1 + rint;

for (j=0; j < rint*1000; j++) {

dummy=2.345*8.765/1.234;

} // spend time on purpose

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;

}

Q1) Compile then run the above code for 10-20 times. Write a paragraph to explain.

Q2) 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

Q3) Rewrite your code in Q1) replacing threads by processes. Instead of creating two threads to call MakeTransactions, you will use fork() to create a child

process. Both parent and child processes will call procedure MakeTransactions.

Since two processes will not share a common address space, you will need to rewrite code toallocate Bank as a shared variable (by applying shared memory IPC, see Slide M02c).

Other parts (i.e., set up initial values, print the initial values and balance, and print the ending values and balance) stay the same.

Show your implementation code in the written report, compile then run your new process-based code for 10-20 times. Write a paragraph to explain if the race condition still exists.

Q4) Use semaphore system calls to modify your code in Q3 in order 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!